From 0ce976092a634f2d86a691815b399eb8aef624f9 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 26 Sep 2017 13:31:41 -0700 Subject: [PATCH] Update LKG --- lib/lib.d.ts | 398 ++- lib/lib.dom.d.ts | 281 +- lib/lib.es2015.core.d.ts | 31 +- lib/lib.es2015.iterable.d.ts | 100 +- lib/lib.es2015.reflect.d.ts | 4 +- lib/lib.es2015.symbol.wellknown.d.ts | 42 - lib/lib.es2016.full.d.ts | 483 ++- lib/lib.es2017.full.d.ts | 483 ++- lib/lib.es2017.object.d.ts | 6 + lib/lib.es5.d.ts | 92 +- lib/lib.es6.d.ts | 575 ++- lib/lib.esnext.full.d.ts | 483 ++- lib/lib.scripthost.d.ts | 25 +- lib/lib.webworker.d.ts | 72 +- lib/tsc.js | 2914 ++++++++------- lib/tsserver.js | 4771 +++++++++++++----------- lib/tsserverlibrary.d.ts | 199 +- lib/tsserverlibrary.js | 4687 +++++++++++++----------- lib/typescript.d.ts | 231 +- lib/typescript.js | 4975 +++++++++++++++----------- lib/typescriptServices.d.ts | 231 +- lib/typescriptServices.js | 4975 +++++++++++++++----------- lib/typingsInstaller.js | 966 +++-- 23 files changed, 15252 insertions(+), 11772 deletions(-) diff --git a/lib/lib.d.ts b/lib/lib.d.ts index c99bf56ef4362..7074d06c1a9b2 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -147,7 +147,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined; /** * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly @@ -1597,7 +1597,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1608,7 +1608,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1764,8 +1764,8 @@ interface Int8Array { interface Int8ArrayConstructor { readonly prototype: Int8Array; new(length: number): Int8Array; - new(array: ArrayLike): Int8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1864,7 +1864,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1875,7 +1875,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2032,8 +2032,8 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new(length: number): Uint8Array; - new(array: ArrayLike): Uint8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,7 +2131,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2142,7 +2142,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2299,8 +2299,8 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new(length: number): Uint8ClampedArray; - new(array: ArrayLike): Uint8ClampedArray; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2386,7 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2397,7 +2397,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2408,7 +2408,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2564,8 +2564,8 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; new(length: number): Int16Array; - new(array: ArrayLike): Int16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2664,7 +2664,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2675,7 +2675,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2832,8 +2832,8 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new(length: number): Uint16Array; - new(array: ArrayLike): Uint16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2931,7 +2931,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2942,7 +2942,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3099,8 +3099,8 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; new(length: number): Int32Array; - new(array: ArrayLike): Int32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3198,7 +3198,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3209,7 +3209,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3365,8 +3365,8 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new(length: number): Uint32Array; - new(array: ArrayLike): Uint32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3464,7 +3464,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3475,7 +3475,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3632,8 +3632,8 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; new(length: number): Float32Array; - new(array: ArrayLike): Float32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3732,7 +3732,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3743,7 +3743,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3790,7 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3900,8 +3900,8 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; new(length: number): Float64Array; - new(array: ArrayLike): Float64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4088,11 +4088,11 @@ interface Date { ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -4119,11 +4119,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -4171,9 +4171,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -4181,30 +4181,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -4245,15 +4245,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -4268,7 +4268,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -4276,8 +4276,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -4287,19 +4287,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -4321,12 +4322,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -4349,7 +4350,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -4357,7 +4358,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -4434,7 +4435,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -4442,8 +4443,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -4526,7 +4527,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -4736,8 +4737,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -4763,9 +4764,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -4779,19 +4780,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -4806,9 +4807,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -4856,7 +4857,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -4868,7 +4869,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -4953,15 +4954,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -5171,9 +5172,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -5184,29 +5185,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -5214,7 +5215,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -5224,7 +5225,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -5604,9 +5605,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -5618,7 +5619,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -6723,7 +6724,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -7462,7 +7463,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -7968,7 +7969,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -8128,7 +8129,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -8366,7 +8367,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -8799,7 +8800,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -9378,7 +9379,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -9545,7 +9546,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -9567,7 +9568,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -10001,7 +10002,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -10100,7 +10101,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -10139,7 +10140,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -10183,7 +10184,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -10272,7 +10273,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -10358,7 +10359,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -10829,7 +10830,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -11295,6 +11296,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -11396,7 +11398,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -13142,6 +13144,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -13595,8 +13598,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -13632,7 +13635,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -15657,7 +15660,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -15965,6 +15968,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -17826,13 +17830,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -17907,17 +17911,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -18008,8 +18032,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -18285,6 +18308,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -18774,7 +18835,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -19078,10 +19139,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -19107,8 +19176,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -19116,7 +19186,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -19148,8 +19218,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -19157,7 +19226,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index c96d5463b9ced..948510a2bc386 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -24,11 +24,11 @@ and limitations under the License. ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -55,11 +55,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -107,9 +107,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -117,30 +117,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -181,15 +181,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -204,7 +204,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -212,8 +212,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -223,19 +223,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -257,12 +258,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -285,7 +286,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -293,7 +294,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -370,7 +371,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -378,8 +379,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -462,7 +463,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -672,8 +673,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -699,9 +700,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -715,19 +716,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -742,9 +743,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -792,7 +793,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -804,7 +805,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -889,15 +890,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -1107,9 +1108,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -1120,29 +1121,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -1150,7 +1151,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -1160,7 +1161,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -1540,9 +1541,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -1554,7 +1555,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -2659,7 +2660,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -3398,7 +3399,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -3904,7 +3905,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -4064,7 +4065,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -4302,7 +4303,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -4735,7 +4736,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -5314,7 +5315,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -5481,7 +5482,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -5503,7 +5504,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -5937,7 +5938,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -6036,7 +6037,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -6075,7 +6076,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -6119,7 +6120,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -6208,7 +6209,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -6294,7 +6295,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -6765,7 +6766,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -7231,6 +7232,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -7332,7 +7334,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -9078,6 +9080,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -9531,8 +9534,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -9568,7 +9571,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -11593,7 +11596,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -11901,6 +11904,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -13762,13 +13766,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -13843,17 +13847,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -13944,8 +13968,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -14221,6 +14244,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14710,7 +14771,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index bf2edb82ca676..610c46abc6010 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -30,9 +30,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -43,9 +41,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -76,22 +72,13 @@ interface ArrayConstructor { * @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, mapfn: (this: void, v: T, k: number) => U): Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; + from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: T[]): Array; + of(...items: T[]): T[]; } interface DateConstructor { @@ -360,7 +347,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. @@ -383,9 +370,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -396,9 +381,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; } interface RegExp { diff --git a/lib/lib.es2015.iterable.d.ts b/lib/lib.es2015.iterable.d.ts index 551698607ca79..edf2dbc77600c 100644 --- a/lib/lib.es2015.iterable.d.ts +++ b/lib/lib.es2015.iterable.d.ts @@ -74,15 +74,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; + from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -237,10 +229,6 @@ interface String { [Symbol.iterator](): IterableIterator; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { [Symbol.iterator](): IterableIterator; /** @@ -266,17 +254,9 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; - - from(arrayLike: Iterable): Int8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { [Symbol.iterator](): IterableIterator; /** @@ -302,17 +282,9 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: Iterable): Uint8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator; /** @@ -341,17 +313,9 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: Iterable): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { [Symbol.iterator](): IterableIterator; /** @@ -379,17 +343,9 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; - - from(arrayLike: Iterable): Int16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { [Symbol.iterator](): IterableIterator; /** @@ -415,17 +371,9 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; - - from(arrayLike: Iterable): Uint16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { [Symbol.iterator](): IterableIterator; /** @@ -451,17 +399,9 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; - - from(arrayLike: Iterable): Int32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { [Symbol.iterator](): IterableIterator; /** @@ -487,17 +427,9 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; - - from(arrayLike: Iterable): Uint32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { [Symbol.iterator](): IterableIterator; /** @@ -523,17 +455,9 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; - - from(arrayLike: Iterable): Float32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { [Symbol.iterator](): IterableIterator; /** @@ -559,9 +483,5 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; - - from(arrayLike: Iterable): Float64Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } diff --git a/lib/lib.es2015.reflect.d.ts b/lib/lib.es2015.reflect.d.ts index 2bea5f1e59b02..1139f1c2c89f1 100644 --- a/lib/lib.es2015.reflect.d.ts +++ b/lib/lib.es2015.reflect.d.ts @@ -24,11 +24,11 @@ declare namespace Reflect { function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; - function ownKeys(target: object): Array; + function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index f323260bf896d..5017ec92da5a0 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -260,12 +260,6 @@ interface String { split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } @@ -274,74 +268,38 @@ interface DataView { readonly [Symbol.toStringTag]: "DataView"; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index 07c6a3e8283e6..522e29a1034bf 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -33,9 +33,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -46,9 +44,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -79,22 +75,13 @@ interface ArrayConstructor { * @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, mapfn: (this: void, v: T, k: number) => U): Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; + from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: T[]): Array; + of(...items: T[]): T[]; } interface DateConstructor { @@ -363,7 +350,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. @@ -386,9 +373,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -399,9 +384,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; } interface RegExp { @@ -741,15 +724,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; + from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -904,10 +879,6 @@ interface String { [Symbol.iterator](): IterableIterator; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { [Symbol.iterator](): IterableIterator; /** @@ -933,17 +904,9 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; - - from(arrayLike: Iterable): Int8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { [Symbol.iterator](): IterableIterator; /** @@ -969,17 +932,9 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: Iterable): Uint8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator; /** @@ -1008,17 +963,9 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: Iterable): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { [Symbol.iterator](): IterableIterator; /** @@ -1046,17 +993,9 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; - - from(arrayLike: Iterable): Int16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { [Symbol.iterator](): IterableIterator; /** @@ -1082,17 +1021,9 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; - - from(arrayLike: Iterable): Uint16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { [Symbol.iterator](): IterableIterator; /** @@ -1118,17 +1049,9 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; - - from(arrayLike: Iterable): Int32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { [Symbol.iterator](): IterableIterator; /** @@ -1154,17 +1077,9 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; - - from(arrayLike: Iterable): Uint32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { [Symbol.iterator](): IterableIterator; /** @@ -1190,17 +1105,9 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; - - from(arrayLike: Iterable): Float32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { [Symbol.iterator](): IterableIterator; /** @@ -1226,11 +1133,7 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; - - from(arrayLike: Iterable): Float64Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } @@ -1468,11 +1371,11 @@ declare namespace Reflect { function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; - function ownKeys(target: object): Array; + function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; @@ -1758,12 +1661,6 @@ interface String { split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } @@ -1772,74 +1669,38 @@ interface DataView { readonly [Symbol.toStringTag]: "DataView"; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } @@ -1851,11 +1712,11 @@ interface Float64Array { ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -1882,11 +1743,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -1934,9 +1795,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -1944,30 +1805,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -2008,15 +1869,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -2031,7 +1892,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -2039,8 +1900,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -2050,19 +1911,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -2084,12 +1946,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -2112,7 +1974,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -2120,7 +1982,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -2197,7 +2059,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -2205,8 +2067,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -2289,7 +2151,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -2499,8 +2361,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -2526,9 +2388,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -2542,19 +2404,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -2569,9 +2431,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -2619,7 +2481,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -2631,7 +2493,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -2716,15 +2578,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -2934,9 +2796,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -2947,29 +2809,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -2977,7 +2839,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -2987,7 +2849,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -3367,9 +3229,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -3381,7 +3243,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -4486,7 +4348,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -5225,7 +5087,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -5731,7 +5593,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -5891,7 +5753,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -6129,7 +5991,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -6562,7 +6424,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -7141,7 +7003,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -7308,7 +7170,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -7330,7 +7192,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7764,7 +7626,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -7863,7 +7725,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7902,7 +7764,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7946,7 +7808,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -8035,7 +7897,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -8121,7 +7983,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -8592,7 +8454,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -9058,6 +8920,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -9159,7 +9022,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -10905,6 +10768,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -11358,8 +11222,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11395,7 +11259,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -13420,7 +13284,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -13728,6 +13592,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -15589,13 +15454,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -15670,17 +15535,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -15771,8 +15656,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -16048,6 +15932,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16537,7 +16459,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16841,10 +16763,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -16870,8 +16800,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -16879,7 +16810,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -16911,8 +16842,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -16920,7 +16850,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 331f822c6fe12..96b589afafab7 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -37,9 +37,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -50,9 +48,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -83,22 +79,13 @@ interface ArrayConstructor { * @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, mapfn: (this: void, v: T, k: number) => U): Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; + from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: T[]): Array; + of(...items: T[]): T[]; } interface DateConstructor { @@ -367,7 +354,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. @@ -390,9 +377,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -403,9 +388,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; } interface RegExp { @@ -745,15 +728,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; + from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -908,10 +883,6 @@ interface String { [Symbol.iterator](): IterableIterator; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { [Symbol.iterator](): IterableIterator; /** @@ -937,17 +908,9 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; - - from(arrayLike: Iterable): Int8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { [Symbol.iterator](): IterableIterator; /** @@ -973,17 +936,9 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: Iterable): Uint8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator; /** @@ -1012,17 +967,9 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: Iterable): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { [Symbol.iterator](): IterableIterator; /** @@ -1050,17 +997,9 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; - - from(arrayLike: Iterable): Int16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { [Symbol.iterator](): IterableIterator; /** @@ -1086,17 +1025,9 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; - - from(arrayLike: Iterable): Uint16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { [Symbol.iterator](): IterableIterator; /** @@ -1122,17 +1053,9 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; - - from(arrayLike: Iterable): Int32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { [Symbol.iterator](): IterableIterator; /** @@ -1158,17 +1081,9 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; - - from(arrayLike: Iterable): Uint32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { [Symbol.iterator](): IterableIterator; /** @@ -1194,17 +1109,9 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; - - from(arrayLike: Iterable): Float32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { [Symbol.iterator](): IterableIterator; /** @@ -1230,11 +1137,7 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; - - from(arrayLike: Iterable): Float64Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } @@ -1472,11 +1375,11 @@ declare namespace Reflect { function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; - function ownKeys(target: object): Array; + function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; @@ -1762,12 +1665,6 @@ interface String { split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } @@ -1776,74 +1673,38 @@ interface DataView { readonly [Symbol.toStringTag]: "DataView"; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } @@ -1855,11 +1716,11 @@ interface Float64Array { ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -1886,11 +1747,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -1938,9 +1799,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -1948,30 +1809,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -2012,15 +1873,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -2035,7 +1896,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -2043,8 +1904,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -2054,19 +1915,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -2088,12 +1950,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -2116,7 +1978,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -2124,7 +1986,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -2201,7 +2063,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -2209,8 +2071,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -2293,7 +2155,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -2503,8 +2365,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -2530,9 +2392,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -2546,19 +2408,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -2573,9 +2435,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -2623,7 +2485,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -2635,7 +2497,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -2720,15 +2582,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -2938,9 +2800,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -2951,29 +2813,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -2981,7 +2843,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -2991,7 +2853,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -3371,9 +3233,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -3385,7 +3247,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -4490,7 +4352,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -5229,7 +5091,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -5735,7 +5597,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -5895,7 +5757,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -6133,7 +5995,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -6566,7 +6428,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -7145,7 +7007,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -7312,7 +7174,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -7334,7 +7196,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7768,7 +7630,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -7867,7 +7729,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7906,7 +7768,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7950,7 +7812,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -8039,7 +7901,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -8125,7 +7987,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -8596,7 +8458,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -9062,6 +8924,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -9163,7 +9026,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -10909,6 +10772,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -11362,8 +11226,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11399,7 +11263,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -13424,7 +13288,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -13732,6 +13596,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -15593,13 +15458,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -15674,17 +15539,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -15775,8 +15660,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -16052,6 +15936,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16541,7 +16463,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16845,10 +16767,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -16874,8 +16804,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -16883,7 +16814,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -16915,8 +16846,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -16924,7 +16854,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index 00c11be275d5c..7eecc25680df0 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -42,4 +42,10 @@ interface ObjectConstructor { * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ entries(o: any): [string, any][]; + + /** + * Returns an object containing all own property descriptors of an object + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + getOwnPropertyDescriptors(o: T): {[P in keyof T]: TypedPropertyDescriptor} & { [x: string]: PropertyDescriptor }; } diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 8353dc1500f69..73aa450927d8b 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -147,7 +147,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined; /** * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly @@ -1597,7 +1597,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1608,7 +1608,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1764,8 +1764,8 @@ interface Int8Array { interface Int8ArrayConstructor { readonly prototype: Int8Array; new(length: number): Int8Array; - new(array: ArrayLike): Int8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1864,7 +1864,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1875,7 +1875,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2032,8 +2032,8 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new(length: number): Uint8Array; - new(array: ArrayLike): Uint8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,7 +2131,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2142,7 +2142,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2299,8 +2299,8 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new(length: number): Uint8ClampedArray; - new(array: ArrayLike): Uint8ClampedArray; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2386,7 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2397,7 +2397,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2408,7 +2408,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2564,8 +2564,8 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; new(length: number): Int16Array; - new(array: ArrayLike): Int16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2664,7 +2664,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2675,7 +2675,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2832,8 +2832,8 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new(length: number): Uint16Array; - new(array: ArrayLike): Uint16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2931,7 +2931,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2942,7 +2942,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3099,8 +3099,8 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; new(length: number): Int32Array; - new(array: ArrayLike): Int32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3198,7 +3198,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3209,7 +3209,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3365,8 +3365,8 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new(length: number): Uint32Array; - new(array: ArrayLike): Uint32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3464,7 +3464,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3475,7 +3475,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3632,8 +3632,8 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; new(length: number): Float32Array; - new(array: ArrayLike): Float32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3732,7 +3732,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3743,7 +3743,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3790,7 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3900,8 +3900,8 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; new(length: number): Float64Array; - new(array: ArrayLike): Float64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index b44acacc87259..a84a66e1293e1 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -147,7 +147,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined; /** * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly @@ -1597,7 +1597,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1608,7 +1608,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1764,8 +1764,8 @@ interface Int8Array { interface Int8ArrayConstructor { readonly prototype: Int8Array; new(length: number): Int8Array; - new(array: ArrayLike): Int8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1864,7 +1864,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1875,7 +1875,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2032,8 +2032,8 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new(length: number): Uint8Array; - new(array: ArrayLike): Uint8Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,7 +2131,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2142,7 +2142,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2299,8 +2299,8 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new(length: number): Uint8ClampedArray; - new(array: ArrayLike): Uint8ClampedArray; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2386,7 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2397,7 +2397,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2408,7 +2408,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2564,8 +2564,8 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; new(length: number): Int16Array; - new(array: ArrayLike): Int16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2664,7 +2664,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2675,7 +2675,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2832,8 +2832,8 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new(length: number): Uint16Array; - new(array: ArrayLike): Uint16Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2931,7 +2931,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2942,7 +2942,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3099,8 +3099,8 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; new(length: number): Int32Array; - new(array: ArrayLike): Int32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3198,7 +3198,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3209,7 +3209,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3365,8 +3365,8 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new(length: number): Uint32Array; - new(array: ArrayLike): Uint32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3464,7 +3464,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3475,7 +3475,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3632,8 +3632,8 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; new(length: number): Float32Array; - new(array: ArrayLike): Float32Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3732,7 +3732,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3743,7 +3743,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3790,7 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3900,8 +3900,8 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; new(length: number): Float64Array; - new(array: ArrayLike): Float64Array; - new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4094,9 +4094,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -4107,9 +4105,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -4140,22 +4136,13 @@ interface ArrayConstructor { * @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, mapfn: (this: void, v: T, k: number) => U): Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; + from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: T[]): Array; + of(...items: T[]): T[]; } interface DateConstructor { @@ -4424,7 +4411,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. @@ -4447,9 +4434,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -4460,9 +4445,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; } interface RegExp { @@ -4802,15 +4785,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; + from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -4965,10 +4940,6 @@ interface String { [Symbol.iterator](): IterableIterator; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { [Symbol.iterator](): IterableIterator; /** @@ -4994,17 +4965,9 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; - - from(arrayLike: Iterable): Int8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { [Symbol.iterator](): IterableIterator; /** @@ -5030,17 +4993,9 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: Iterable): Uint8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator; /** @@ -5069,17 +5024,9 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: Iterable): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { [Symbol.iterator](): IterableIterator; /** @@ -5107,17 +5054,9 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; - - from(arrayLike: Iterable): Int16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { [Symbol.iterator](): IterableIterator; /** @@ -5143,17 +5082,9 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; - - from(arrayLike: Iterable): Uint16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { [Symbol.iterator](): IterableIterator; /** @@ -5179,17 +5110,9 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; - - from(arrayLike: Iterable): Int32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { [Symbol.iterator](): IterableIterator; /** @@ -5215,17 +5138,9 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; - - from(arrayLike: Iterable): Uint32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { [Symbol.iterator](): IterableIterator; /** @@ -5251,17 +5166,9 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; - - from(arrayLike: Iterable): Float32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { [Symbol.iterator](): IterableIterator; /** @@ -5287,11 +5194,7 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; - - from(arrayLike: Iterable): Float64Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } @@ -5529,11 +5432,11 @@ declare namespace Reflect { function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; - function ownKeys(target: object): Array; + function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; @@ -5819,12 +5722,6 @@ interface String { split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } @@ -5833,74 +5730,38 @@ interface DataView { readonly [Symbol.toStringTag]: "DataView"; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } @@ -5912,11 +5773,11 @@ interface Float64Array { ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -5943,11 +5804,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -5995,9 +5856,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -6005,30 +5866,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -6069,15 +5930,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -6092,7 +5953,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -6100,8 +5961,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -6111,19 +5972,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -6145,12 +6007,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -6173,7 +6035,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -6181,7 +6043,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -6258,7 +6120,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -6266,8 +6128,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -6350,7 +6212,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -6560,8 +6422,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -6587,9 +6449,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -6603,19 +6465,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -6630,9 +6492,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -6680,7 +6542,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -6692,7 +6554,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -6777,15 +6639,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -6995,9 +6857,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -7008,29 +6870,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -7038,7 +6900,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -7048,7 +6910,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -7428,9 +7290,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -7442,7 +7304,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -8547,7 +8409,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -9286,7 +9148,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -9792,7 +9654,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -9952,7 +9814,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -10190,7 +10052,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -10623,7 +10485,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -11202,7 +11064,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -11369,7 +11231,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -11391,7 +11253,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -11825,7 +11687,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -11924,7 +11786,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -11963,7 +11825,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -12007,7 +11869,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -12096,7 +11958,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -12182,7 +12044,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -12653,7 +12515,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -13119,6 +12981,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -13220,7 +13083,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -14966,6 +14829,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -15419,8 +15283,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -15456,7 +15320,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -17481,7 +17345,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -17789,6 +17653,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -19650,13 +19515,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -19731,17 +19596,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -19832,8 +19717,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -20109,6 +19993,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -20598,7 +20520,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -20902,10 +20824,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -20931,8 +20861,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -20940,7 +20871,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -20972,8 +20903,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -20981,7 +20911,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index f7b59da300237..4ee476dfd1a42 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -34,9 +34,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -47,9 +45,7 @@ interface Array { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number; /** * Returns the this object after filling the section identified by start and end with value @@ -80,22 +76,13 @@ interface ArrayConstructor { * @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, mapfn: (this: void, v: T, k: number) => U): Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - - /** - * Creates an array from an array-like object. - * @param arrayLike An array-like object to convert to an array. - */ - from(arrayLike: ArrayLike): Array; + from(arrayLike: ArrayLike, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: T[]): Array; + of(...items: T[]): T[]; } interface DateConstructor { @@ -364,7 +351,7 @@ interface ObjectConstructor { * @param o Object that contains the property. * @param p Name of the property. */ - getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor; + getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined; /** * Adds a property to an object, or modifies attributes of an existing property. @@ -387,9 +374,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean): T | undefined; - find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: undefined): T | undefined; - find(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray) => boolean, thisArg: Z): T | undefined; + find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -400,9 +385,7 @@ interface ReadonlyArray { * @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: (this: void, value: T, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: T, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: T, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number; } interface RegExp { @@ -742,15 +725,7 @@ interface ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U): Array; - from(iterable: Iterable, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array; - from(iterable: Iterable, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array; - - /** - * Creates an array from an iterable object. - * @param iterable An iterable object to convert to an array. - */ - from(iterable: Iterable): Array; + from(iterable: Iterable, mapfn?: (v: T, k: number) => U, thisArg?: any): U[]; } interface ReadonlyArray { @@ -905,10 +880,6 @@ interface String { [Symbol.iterator](): IterableIterator; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { [Symbol.iterator](): IterableIterator; /** @@ -934,17 +905,9 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; - - from(arrayLike: Iterable): Int8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { [Symbol.iterator](): IterableIterator; /** @@ -970,17 +933,9 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: Iterable): Uint8Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { [Symbol.iterator](): IterableIterator; /** @@ -1009,17 +964,9 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: Iterable): Uint8ClampedArray; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { [Symbol.iterator](): IterableIterator; /** @@ -1047,17 +994,9 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; - - from(arrayLike: Iterable): Int16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { [Symbol.iterator](): IterableIterator; /** @@ -1083,17 +1022,9 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; - - from(arrayLike: Iterable): Uint16Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { [Symbol.iterator](): IterableIterator; /** @@ -1119,17 +1050,9 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Int32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; - - from(arrayLike: Iterable): Int32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { [Symbol.iterator](): IterableIterator; /** @@ -1155,17 +1078,9 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; - - from(arrayLike: Iterable): Uint32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { [Symbol.iterator](): IterableIterator; /** @@ -1191,17 +1106,9 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float32Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; - - from(arrayLike: Iterable): Float32Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { [Symbol.iterator](): IterableIterator; /** @@ -1227,11 +1134,7 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number): Float64Array; - from(arrayLike: Iterable, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: Iterable, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; - - from(arrayLike: Iterable): Float64Array; + from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } @@ -1469,11 +1372,11 @@ declare namespace Reflect { function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; function deleteProperty(target: object, propertyKey: PropertyKey): boolean; function get(target: object, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; + function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined; function getPrototypeOf(target: object): object; function has(target: object, propertyKey: PropertyKey): boolean; function isExtensible(target: object): boolean; - function ownKeys(target: object): Array; + function ownKeys(target: object): PropertyKey[]; function preventExtensions(target: object): boolean; function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; function setPrototypeOf(target: object, proto: any): boolean; @@ -1759,12 +1662,6 @@ interface String { split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; } -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ interface ArrayBuffer { readonly [Symbol.toStringTag]: "ArrayBuffer"; } @@ -1773,74 +1670,38 @@ interface DataView { readonly [Symbol.toStringTag]: "DataView"; } -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint8Array { readonly [Symbol.toStringTag]: "UInt8Array"; } -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } @@ -1852,11 +1713,11 @@ interface Float64Array { ///////////////////////////// interface Account { - displayName?: string; - id?: string; + displayName: string; + id: string; imageURL?: string; name?: string; - rpDisplayName?: string; + rpDisplayName: string; } interface Algorithm { @@ -1883,11 +1744,11 @@ interface CacheQueryOptions { } interface ClientData { - challenge?: string; + challenge: string; extensions?: WebAuthnExtensions; - hashAlg?: string | Algorithm; - origin?: string; - rpId?: string; + hashAlg: string | Algorithm; + origin: string; + rpId: string; tokenBinding?: string; } @@ -1935,9 +1796,9 @@ interface CustomEventInit extends EventInit { } interface DeviceAccelerationDict { - x?: number; - y?: number; - z?: number; + x?: number | null; + y?: number | null; + z?: number | null; } interface DeviceLightEventInit extends EventInit { @@ -1945,30 +1806,30 @@ interface DeviceLightEventInit extends EventInit { } interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceAccelerationDict; - accelerationIncludingGravity?: DeviceAccelerationDict; - interval?: number; - rotationRate?: DeviceRotationRateDict; + acceleration?: DeviceAccelerationDict | null; + accelerationIncludingGravity?: DeviceAccelerationDict | null; + interval?: number | null; + rotationRate?: DeviceRotationRateDict | null; } interface DeviceOrientationEventInit extends EventInit { absolute?: boolean; - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DeviceRotationRateDict { - alpha?: number; - beta?: number; - gamma?: number; + alpha?: number | null; + beta?: number | null; + gamma?: number | null; } interface DOMRectInit { - height?: any; - width?: any; - x?: any; - y?: any; + height?: number; + width?: number; + x?: number; + y?: number; } interface DoubleRange { @@ -2009,15 +1870,15 @@ interface EventModifierInit extends UIEventInit { } interface ExceptionInformation { - domain?: string; + domain?: string | null; } interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; } interface FocusNavigationEventInit extends EventInit { - navigationReason?: string; + navigationReason?: string | null; originHeight?: number; originLeft?: number; originTop?: number; @@ -2032,7 +1893,7 @@ interface FocusNavigationOrigin { } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad?: Gamepad | null; } interface GetNotificationOptions { @@ -2040,8 +1901,8 @@ interface GetNotificationOptions { } interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; + newURL?: string | null; + oldURL?: string | null; } interface IDBIndexParameters { @@ -2051,19 +1912,20 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface IntersectionObserverEntryInit { - boundingClientRect?: DOMRectInit; - intersectionRect?: DOMRectInit; - rootBounds?: DOMRectInit; - target?: Element; - time?: number; + isIntersecting: boolean; + boundingClientRect: DOMRectInit; + intersectionRect: DOMRectInit; + rootBounds: DOMRectInit; + target: Element; + time: number; } interface IntersectionObserverInit { - root?: Element; + root?: Element | null; rootMargin?: string; threshold?: number | number[]; } @@ -2085,12 +1947,12 @@ interface LongRange { } interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer; + initData?: ArrayBuffer | null; initDataType?: string; } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer; + message?: ArrayBuffer | null; messageType?: MediaKeyMessageType; } @@ -2113,7 +1975,7 @@ interface MediaStreamConstraints { } interface MediaStreamErrorEventInit extends EventInit { - error?: MediaStreamError; + error?: MediaStreamError | null; } interface MediaStreamEventInit extends EventInit { @@ -2121,7 +1983,7 @@ interface MediaStreamEventInit extends EventInit { } interface MediaStreamTrackEventInit extends EventInit { - track?: MediaStreamTrack; + track?: MediaStreamTrack | null; } interface MediaTrackCapabilities { @@ -2198,7 +2060,7 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; - relatedTarget?: EventTarget; + relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; } @@ -2206,8 +2068,8 @@ interface MouseEventInit extends EventModifierInit { interface MSAccountInfo { accountImageUri?: string; accountName?: string; - rpDisplayName?: string; - userDisplayName?: string; + rpDisplayName: string; + userDisplayName: string; userId?: string; } @@ -2290,7 +2152,7 @@ interface MSCredentialParameters { interface MSCredentialSpec { id?: string; - type?: MSCredentialType; + type: MSCredentialType; } interface MSDelay { @@ -2500,8 +2362,8 @@ interface MsZoomToOptions { contentX?: number; contentY?: number; scaleFactor?: number; - viewportX?: string; - viewportY?: string; + viewportX?: string | null; + viewportY?: string | null; } interface MutationObserverInit { @@ -2527,9 +2389,9 @@ interface ObjectURLOptions { } interface PaymentCurrencyAmount { - currency?: string; + currency: string; currencySystem?: string; - value?: string; + value: string; } interface PaymentDetails { @@ -2543,19 +2405,19 @@ interface PaymentDetails { interface PaymentDetailsModifier { additionalDisplayItems?: PaymentItem[]; data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; total?: PaymentItem; } interface PaymentItem { - amount?: PaymentCurrencyAmount; - label?: string; + amount: PaymentCurrencyAmount; + label: string; pending?: boolean; } interface PaymentMethodData { data?: any; - supportedMethods?: string[]; + supportedMethods: string[]; } interface PaymentOptions { @@ -2570,9 +2432,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { - amount?: PaymentCurrencyAmount; - id?: string; - label?: string; + amount: PaymentCurrencyAmount; + id: string; + label: string; selected?: boolean; } @@ -2620,7 +2482,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -2632,7 +2494,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -2717,15 +2579,15 @@ interface RTCIceGatherOptions { } interface RTCIceParameters { - iceLite?: boolean; + iceLite?: boolean | null; password?: string; usernameFragment?: string; } interface RTCIceServer { - credential?: string; + credential?: string | null; urls?: any; - username?: string; + username?: string | null; } interface RTCInboundRTPStreamStats extends RTCRTPStreamStats { @@ -2935,9 +2797,9 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id?: any; + id: any; transports?: Transport[]; - type?: ScopedCredentialType; + type: ScopedCredentialType; } interface ScopedCredentialOptions { @@ -2948,29 +2810,29 @@ interface ScopedCredentialOptions { } interface ScopedCredentialParameters { - algorithm?: string | Algorithm; - type?: ScopedCredentialType; + algorithm: string | Algorithm; + type: ScopedCredentialType; } interface ServiceWorkerMessageEventInit extends EventInit { data?: any; lastEventId?: string; origin?: string; - ports?: MessagePort[]; - source?: ServiceWorker | MessagePort; + ports?: MessagePort[] | null; + source?: ServiceWorker | MessagePort | null; } interface SpeechSynthesisEventInit extends EventInit { charIndex?: number; elapsedTime?: number; name?: string; - utterance?: SpeechSynthesisUtterance; + utterance?: SpeechSynthesisUtterance | null; } interface StoreExceptionsInformation extends ExceptionInformation { - detailURI?: string; - explanationString?: string; - siteName?: string; + detailURI?: string | null; + explanationString?: string | null; + siteName?: string | null; } interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @@ -2978,7 +2840,7 @@ interface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformat } interface TrackEventInit extends EventInit { - track?: VideoTrack | AudioTrack | TextTrack; + track?: VideoTrack | AudioTrack | TextTrack | null; } interface TransitionEventInit extends EventInit { @@ -2988,7 +2850,7 @@ interface TransitionEventInit extends EventInit { interface UIEventInit extends EventInit { detail?: number; - view?: Window; + view?: Window | null; } interface WebAuthnExtensions { @@ -3368,9 +3230,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -3382,7 +3244,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -4487,7 +4349,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly compatMode: string; cookie: string; - readonly currentScript: HTMLScriptElement | SVGScriptElement; + readonly currentScript: HTMLScriptElement | SVGScriptElement | null; readonly defaultView: Window; /** * Sets or gets a value that indicates whether the document can be edited. @@ -5226,7 +5088,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -5732,7 +5594,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface History { @@ -5892,7 +5754,7 @@ interface HTMLAppletElement extends HTMLElement { * Sets or retrieves a character string that can be used to implement your own declare functionality for the object. */ declare: boolean; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -6130,7 +5992,7 @@ interface HTMLButtonElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -6563,7 +6425,7 @@ interface HTMLFieldSetElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; name: string; /** * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. @@ -7142,7 +7004,7 @@ interface HTMLInputElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Overrides the action attribute (where the data on a form is sent) on the parent form element. */ @@ -7309,7 +7171,7 @@ interface HTMLLabelElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the object to which the given label object is assigned. */ @@ -7331,7 +7193,7 @@ interface HTMLLegendElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -7765,7 +7627,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the height of the object. */ @@ -7864,7 +7726,7 @@ interface HTMLOptGroupElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7903,7 +7765,7 @@ interface HTMLOptionElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the ordinal position of an option in a list box. */ @@ -7947,7 +7809,7 @@ declare var HTMLOptionsCollection: { interface HTMLOutputElement extends HTMLElement { defaultValue: string; - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; readonly htmlFor: DOMSettableTokenList; name: string; readonly type: string; @@ -8036,7 +7898,7 @@ interface HTMLProgressElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Defines the maximum, or "done" value for a progress element. */ @@ -8122,7 +7984,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the number of objects in a collection. */ @@ -8593,7 +8455,7 @@ interface HTMLTextAreaElement extends HTMLElement { /** * Retrieves a reference to the form that the object is embedded in. */ - readonly form: HTMLFormElement; + readonly form: HTMLFormElement | null; /** * Sets or retrieves the maximum number of characters that the user can enter in a text control. */ @@ -9059,6 +8921,7 @@ interface IntersectionObserverEntry { readonly rootBounds: ClientRect; readonly target: Element; readonly time: number; + readonly isIntersecting: boolean; } declare var IntersectionObserverEntry: { @@ -9160,7 +9023,7 @@ interface MediaDevicesEventMap { interface MediaDevices extends EventTarget { ondevicechange: (this: MediaDevices, ev: Event) => any; - enumerateDevices(): any; + enumerateDevices(): Promise; getSupportedConstraints(): MediaTrackSupportedConstraints; getUserMedia(constraints: MediaStreamConstraints): Promise; addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, useCapture?: boolean): void; @@ -10906,6 +10769,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -11359,8 +11223,8 @@ interface ServiceWorkerContainer extends EventTarget { oncontrollerchange: (this: ServiceWorkerContainer, ev: Event) => any; onmessage: (this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any; readonly ready: Promise; - getRegistration(clientURL?: USVString): Promise; - getRegistrations(): any; + getRegistration(): Promise; + getRegistrations(): Promise; register(scriptURL: USVString, options?: RegistrationOptions): Promise; addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11396,7 +11260,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -13421,7 +13285,7 @@ declare var SVGZoomEvent: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -13729,6 +13593,7 @@ interface ValidityState { readonly typeMismatch: boolean; readonly valid: boolean; readonly valueMissing: boolean; + readonly tooShort: boolean; } declare var ValidityState: { @@ -15590,13 +15455,13 @@ interface NavigatorUserMedia { interface NodeSelector { querySelector(selectors: K): ElementTagNameMap[K] | null; - querySelector(selectors: string): Element | null; + querySelector(selectors: string): E | null; querySelectorAll(selectors: K): ElementListTagNameMap[K]; - querySelectorAll(selectors: string): NodeListOf; + querySelectorAll(selectors: string): NodeListOf; } interface RandomSource { - getRandomValues(array: ArrayBufferView): ArrayBufferView; + getRandomValues(array: T): T; } interface SVGAnimatedPoints { @@ -15671,17 +15536,37 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -15772,8 +15657,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } @@ -16049,6 +15933,44 @@ interface TouchEventInit extends EventModifierInit { changedTouches?: Touch[]; } +interface HTMLDialogElement extends HTMLElement { + open: boolean; + returnValue: string; + close(returnValue?: string): void; + show(): void; + showModal(): void; +} + +declare var HTMLDialogElement: { + prototype: HTMLDialogElement; + new(): HTMLDialogElement; +}; + +interface HTMLMainElement extends HTMLElement { +} + +declare var HTMLMainElement: { + prototype: HTMLMainElement; + new(): HTMLMainElement; +}; + +interface HTMLDetailsElement extends HTMLElement { + open: boolean; +} + +declare var HTMLDetailsElement: { + prototype: HTMLDetailsElement; + new(): HTMLDetailsElement; +}; + +interface HTMLSummaryElement extends HTMLElement { +} + +declare var HTMLSummaryElement: { + prototype: HTMLSummaryElement; + new(): HTMLSummaryElement; +}; + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -16538,7 +16460,7 @@ type GLsizeiptr = number; type GLubyte = number; type GLuint = number; type GLushort = number; -type HeadersInit = any; +type HeadersInit = Headers | string[][]; type IDBKeyPath = string; type KeyFormat = string; type KeyType = string; @@ -16842,10 +16764,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -16871,8 +16801,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -16880,7 +16811,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -16912,8 +16843,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -16921,7 +16851,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.scripthost.d.ts b/lib/lib.scripthost.d.ts index 47cfaa7fb8c79..149653a89710d 100644 --- a/lib/lib.scripthost.d.ts +++ b/lib/lib.scripthost.d.ts @@ -221,10 +221,18 @@ declare var WScript: { Sleep(intTime: number): void; }; +/** + * Represents an Automation SAFEARRAY + */ +declare class SafeArray { + private constructor(); + private SafeArray_typekey: SafeArray; +} + /** * Allows enumerating over a COM collection, which may not have indexed item access. */ -interface Enumerator { +interface Enumerator { /** * Returns true if the current item is the last one in the collection, or the collection is empty, * or the current item is undefined. @@ -250,8 +258,9 @@ interface Enumerator { } interface EnumeratorConstructor { - new (collection: any): Enumerator; - new (collection: any): Enumerator; + new (safearray: SafeArray): Enumerator; + new (collection: { Item(index: any): T }): Enumerator; + new (collection: any): Enumerator; } declare var Enumerator: EnumeratorConstructor; @@ -259,7 +268,7 @@ declare var Enumerator: EnumeratorConstructor; /** * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. */ -interface VBArray { +interface VBArray { /** * Returns the number of dimensions (1-based). */ @@ -291,8 +300,7 @@ interface VBArray { } interface VBArrayConstructor { - new (safeArray: any): VBArray; - new (safeArray: any): VBArray; + new (safeArray: SafeArray): VBArray; } declare var VBArray: VBArrayConstructor; @@ -300,7 +308,10 @@ declare var VBArray: VBArrayConstructor; /** * Automation date (VT_DATE) */ -interface VarDate { } +declare class VarDate { + private constructor(); + private VarDate_typekey: VarDate; +} interface DateConstructor { new (vd: VarDate): Date; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 997b007a8791a..f87d32110a64e 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -57,7 +57,7 @@ interface IDBIndexParameters { interface IDBObjectStoreParameters { autoIncrement?: boolean; - keyPath?: IDBKeyPath; + keyPath?: IDBKeyPath | null; } interface KeyAlgorithm { @@ -94,7 +94,7 @@ interface RequestInit { body?: any; cache?: RequestCache; credentials?: RequestCredentials; - headers?: any; + headers?: Headers | string[][]; integrity?: string; keepalive?: boolean; method?: string; @@ -106,7 +106,7 @@ interface RequestInit { } interface ResponseInit { - headers?: any; + headers?: Headers | string[][]; status?: number; statusText?: string; } @@ -123,18 +123,18 @@ interface ExtendableMessageEventInit extends ExtendableEventInit { data?: any; origin?: string; lastEventId?: string; - source?: Client | ServiceWorker | MessagePort; - ports?: MessagePort[]; + source?: Client | ServiceWorker | MessagePort | null; + ports?: MessagePort[] | null; } interface FetchEventInit extends ExtendableEventInit { - request?: Request; - clientId?: string; + request: Request; + clientId?: string | null; isReload?: boolean; } interface NotificationEventInit extends ExtendableEventInit { - notification?: Notification; + notification: Notification; action?: string; } @@ -143,7 +143,7 @@ interface PushEventInit extends ExtendableEventInit { } interface SyncEventInit extends ExtendableEventInit { - tag?: string; + tag: string; lastChance?: boolean; } @@ -195,9 +195,9 @@ interface Cache { add(request: RequestInfo): Promise; addAll(requests: RequestInfo[]): Promise; delete(request: RequestInfo, options?: CacheQueryOptions): Promise; - keys(request?: RequestInfo, options?: CacheQueryOptions): any; + keys(request?: RequestInfo, options?: CacheQueryOptions): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; - matchAll(request?: RequestInfo, options?: CacheQueryOptions): any; + matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise; put(request: RequestInfo, response: Response): Promise; } @@ -209,7 +209,7 @@ declare var Cache: { interface CacheStorage { delete(cacheName: string): Promise; has(cacheName: string): Promise; - keys(): any; + keys(): Promise; match(request: RequestInfo, options?: CacheQueryOptions): Promise; open(cacheName: string): Promise; } @@ -334,7 +334,7 @@ interface DOMException { declare var DOMException: { prototype: DOMException; - new(): DOMException; + new(message?: string, name?: string): DOMException; readonly ABORT_ERR: number; readonly DATA_CLONE_ERR: number; readonly DOMSTRING_SIZE_ERR: number; @@ -490,7 +490,7 @@ interface Headers { declare var Headers: { prototype: Headers; - new(init?: any): Headers; + new(init?: Headers | string[][] | object): Headers; }; interface IDBCursor { @@ -980,6 +980,7 @@ interface Response extends Object, Body { readonly statusText: string; readonly type: ResponseType; readonly url: string; + readonly redirected: boolean; clone(): Response; } @@ -1020,7 +1021,7 @@ interface ServiceWorkerRegistration extends EventTarget { readonly scope: USVString; readonly sync: SyncManager; readonly waiting: ServiceWorker | null; - getNotifications(filter?: GetNotificationOptions): any; + getNotifications(filter?: GetNotificationOptions): Promise; showNotification(title: string, options?: NotificationOptions): Promise; unregister(): Promise; update(): Promise; @@ -1034,7 +1035,7 @@ declare var ServiceWorkerRegistration: { }; interface SyncManager { - getTags(): any; + getTags(): Promise; register(tag: string): Promise; } @@ -1268,13 +1269,13 @@ interface XMLHttpRequestEventTargetEventMap { } interface XMLHttpRequestEventTarget { - onabort: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onerror: (this: XMLHttpRequestEventTarget, ev: ErrorEvent) => any; - onload: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onloadend: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - onloadstart: (this: XMLHttpRequestEventTarget, ev: Event) => any; - onprogress: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; - ontimeout: (this: XMLHttpRequestEventTarget, ev: ProgressEvent) => any; + onabort: (this: XMLHttpRequest, ev: Event) => any; + onerror: (this: XMLHttpRequest, ev: ErrorEvent) => any; + onload: (this: XMLHttpRequest, ev: Event) => any; + onloadend: (this: XMLHttpRequest, ev: ProgressEvent) => any; + onloadstart: (this: XMLHttpRequest, ev: Event) => any; + onprogress: (this: XMLHttpRequest, ev: ProgressEvent) => any; + ontimeout: (this: XMLHttpRequest, ev: ProgressEvent) => any; addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -1294,7 +1295,7 @@ declare var Client: { interface Clients { claim(): Promise; get(id: string): Promise; - matchAll(options?: ClientQueryOptions): any; + matchAll(options?: ClientQueryOptions): Promise; openWindow(url: USVString): Promise; } @@ -1519,6 +1520,26 @@ interface WorkerUtils extends Object, WindowBase64 { setTimeout(handler: any, timeout?: any, ...args: any[]): number; } +interface BroadcastChannel extends EventTarget { + readonly name: string; + onmessage: (ev: MessageEvent) => any; + onmessageerror: (ev: MessageEvent) => any; + close(): void; + postMessage(message: any): void; + addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +} + +declare var BroadcastChannel: { + prototype: BroadcastChannel; + new(name: string): BroadcastChannel; +}; + +interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; +} + interface ErrorEventInit { message?: string; filename?: string; @@ -1582,8 +1603,7 @@ interface BlobPropertyBag { endings?: string; } -interface FilePropertyBag { - type?: string; +interface FilePropertyBag extends BlobPropertyBag { lastModified?: number; } diff --git a/lib/tsc.js b/lib/tsc.js index cf9717975cf9e..a6650351530f0 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -695,6 +695,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; @@ -1055,6 +1056,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1087,7 +1089,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; @@ -1154,6 +1157,12 @@ var ts; ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; @@ -1785,6 +1794,26 @@ var ts; return to; } ts.addRange = addRange; + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; function stableSort(array, comparer) { if (comparer === void 0) { comparer = compareValues; } return array @@ -1931,6 +1960,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2095,6 +2134,8 @@ var ts; ts.cast = cast; function noop() { } ts.noop = noop; + function identity(x) { return x; } + ts.identity = identity; function notImplemented() { throw new Error("Not implemented"); } @@ -2171,12 +2212,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2418,12 +2458,8 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2460,7 +2496,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3086,6 +3122,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3223,6 +3263,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); var ts; (function (ts) { @@ -3787,8 +3833,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4108,7 +4154,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4181,6 +4229,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4298,7 +4347,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4403,17 +4452,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -4504,6 +4552,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4551,7 +4600,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); var ts; @@ -4779,7 +4828,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); } return res; } @@ -6169,7 +6218,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -6193,15 +6241,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -6235,7 +6282,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -6357,7 +6404,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } if (node.kind === 286 && node._children.length > 0) { @@ -6394,6 +6441,15 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; + } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -6421,6 +6477,7 @@ var ts; case 16: return "}" + escapeText(node.text, 96) + "`"; case 8: + case 12: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -6518,6 +6575,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155: + case 156: + case 150: + case 157: + case 160: + case 161: + case 273: + case 229: + case 199: + case 230: + case 231: + case 282: + case 228: + case 151: + case 152: + case 153: + case 154: + case 186: + case 187: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -7165,59 +7250,62 @@ var ts; case 8: case 9: case 99: - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: - return parent.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: - return parent.expression === node; - case 214: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215: - case 216: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || - forInStatement.expression === node; - case 184: - case 202: - return node === parent.expression; - case 205: - return node === parent.expression; - case 144: - return node === parent.expression; - case 147: - case 256: - case 255: - case 263: - return true; - case 201: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -7381,14 +7469,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -7396,14 +7476,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7435,22 +7507,17 @@ var ts; getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getParameterSymbolFromJSDoc(node) { if (node.symbol) { return node.symbol; @@ -7476,38 +7543,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -7519,7 +7554,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -7920,9 +7955,9 @@ var ts; || kind === 265; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -8186,13 +8221,17 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" }); + var escapedNullRegExp = /\\0[0-9]/g; function escapeString(s, quoteChar) { var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -8472,7 +8511,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -8481,7 +8520,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -8490,7 +8529,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -9049,6 +9088,41 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + AccessKind[AccessKind["Read"] = 0] = "Read"; + AccessKind[AccessKind["Write"] = 1] = "Write"; + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0; + switch (parent.kind) { + case 193: + case 192: + var operator = parent.operator; + return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; + case 194: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; + case 179: + return parent.name !== node ? 0 : accessKind(parent); + default: + return 0; + } + function writeOrReadWrite() { + return parent.parent && parent.parent.kind === 210 ? 1 : 2; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9327,6 +9401,56 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 208: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210: + var expr = hostNode.expression; + switch (expr.kind) { + case 179: + return expr.name; + case 180: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1: + return undefined; + case 185: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -9346,11 +9470,78 @@ var ts; return undefined; } } + else if (declaration.kind === 283) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getJSDocTypeTag(node) { + var tag = getFirstJSDocTag(node, 281); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -9983,8 +10174,7 @@ var ts; } ts.isToken = isToken; function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; function isLiteralKind(kind) { @@ -10069,16 +10259,27 @@ var ts; return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152: - case 186: case 228: - case 187: case 151: - case 150: + case 152: case 153: case 154: + case 186: + case 187: + return true; + default: + return false; + } + } + function isFunctionLikeKind(kind) { + switch (kind) { + case 150: case 155: case 156: case 157: @@ -10086,10 +10287,15 @@ var ts; case 273: case 161: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; return kind === 152 @@ -10243,52 +10449,61 @@ var ts; || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 91 - || kind === 203 - || kind === 204; - } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179: + case 180: + case 182: + case 181: + case 249: + case 250: + case 183: + case 177: + case 185: + case 178: + case 199: + case 186: + case 71: + case 12: + case 8: + case 9: + case 13: + case 196: + case 86: + case 95: + case 99: + case 101: + case 97: + case 203: + case 204: + case 91: + return true; + default: + return false; + } } function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192: + case 193: + case 188: + case 189: + case 190: + case 191: + case 184: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { case 193: @@ -10301,21 +10516,26 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 289 - || isUnaryExpressionKind(kind); - } function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195: + case 197: + case 187: + case 194: + case 198: + case 202: + case 200: + case 289: + case 288: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 @@ -10556,6 +10776,10 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -10977,9 +11201,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288: @@ -11159,7 +11385,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -11279,9 +11505,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } function token() { return currentToken; } @@ -11404,13 +11627,11 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -11458,7 +11679,8 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var reportAtCurrentPosition = token() === 1; + return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -11691,20 +11913,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -11910,12 +12132,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26)) { continue; @@ -11940,15 +12163,15 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); if (commaStart >= 0) { result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -11990,12 +12213,12 @@ var ts; var template = createNode(196); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -12090,7 +12313,7 @@ var ts; var result = createNode(273); nextToken(); fillSignature(56, 4 | 32, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159); node.typeName = parseIdentifierName(); @@ -12148,9 +12371,10 @@ var ts; return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || isStartOfType(); + token() === 57 || + isStartOfType(true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146); if (token() === 99) { node.name = createIdentifier(true); @@ -12166,37 +12390,33 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); + node.initializer = parseInitializer(true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56)) { + return true; } - else if (flags & 4) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); - if (backwardToken) { - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { if (parseExpected(19)) { @@ -12204,7 +12424,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -12268,7 +12488,7 @@ var ts; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -12400,7 +12620,7 @@ var ts; parseExpected(94); } fillSignature(36, 4, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -12414,16 +12634,9 @@ var ts; unaryMinusExpression.operator = 38; nextToken(); } - var expression; - switch (token()) { - case 9: - case 8: - expression = parseLiteralLikeNode(token()); - break; - case 101: - case 86: - expression = parseTokenNode(); - } + var expression = token() === 101 || token() === 86 + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -12456,6 +12669,7 @@ var ts; return parseJSDocNodeWithType(274); case 51: return parseJSDocNodeWithType(271); + case 13: case 9: case 8: case 101: @@ -12487,7 +12701,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119: case 136: @@ -12512,11 +12726,14 @@ var ts; case 86: case 134: case 39: + case 55: + case 51: + case 24: return true; case 38: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -12582,13 +12799,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -12748,11 +12964,16 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58) { if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { return undefined; } + if (inParameter && requireEqualsToken) { + var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } parseExpected(58); return parseAssignmentExpressionOrHigher(); @@ -12813,8 +13034,7 @@ var ts; var parameter = createNode(146, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); @@ -12921,8 +13141,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -12951,7 +13170,8 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { + if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { return undefined; } return node; @@ -13293,7 +13513,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { @@ -13310,12 +13531,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254); @@ -14194,7 +14414,7 @@ var ts; var node = createNode(176); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { @@ -14210,7 +14430,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingPattern() { @@ -14244,7 +14464,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -14408,7 +14628,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57)) { @@ -14417,20 +14638,13 @@ var ts; var decorator = createNode(147, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); + (list || (list = [])).push(decorator); } - return decorators; + return list && createNodeArray(list, listPos); } function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -14445,17 +14659,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } + (list || (list = [])).push(modifier); } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -14465,7 +14671,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -14960,9 +15165,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267, scanner.getTokenPos()); - parseExpected(17); + if (!parseExpected(17) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576, parseType); parseExpected(18); fixupParentReferences(result); @@ -15019,6 +15226,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; if (!isJsDocStart(content, start)) { @@ -15127,7 +15336,7 @@ var ts; } function createJSDocComment() { var result = createNode(275, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -15250,21 +15459,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { var isBracketed = parseOptional(21); @@ -15354,11 +15559,11 @@ var ts; var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(true); var result = createNode(277, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -15393,19 +15598,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285, start_3); } if (child.kind === 281) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -15419,7 +15623,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -15513,7 +15719,8 @@ var ts; if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name = parseJSDocIdentifierName(); skipWhitespace(); @@ -15536,9 +15743,8 @@ var ts; var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -15630,7 +15836,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -16013,9 +16219,11 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { - symbol.declarations = []; + symbol.declarations = [node]; + } + else { + symbol.declarations.push(node); } - symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } @@ -16079,17 +16287,8 @@ var ts; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; case 283: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (ts.isIdentifier(nameIdentifier)) { - nameFromParentNode = nameIdentifier.escapedText; - } - } - } - return nameFromParentNode; + var name_2 = ts.getNameOfJSDocTypedef(node); + return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -16290,7 +16489,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; @@ -17030,9 +17229,6 @@ var ts; lastContainer = next; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { case 233: return declareModuleMember(node, symbolFlags, symbolExcludes); @@ -17194,6 +17390,9 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & 8) { + symbol.parent = container.symbol; + } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { @@ -17351,7 +17550,7 @@ var ts; inStrictMode = saveInStrictMode; } function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { + if (!ts.hasJSDocNodes(node)) { return; } for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -18528,31 +18727,38 @@ var ts; return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = ts.createMap(); - var visitedSymbols = ts.createMap(); + var visitedTypes = []; + var visitedSymbols = []; return { walkType: function (type) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitType(type); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, walkSymbol: function (symbol) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitSymbol(symbol); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, }; function visitType(type) { if (!type) { return; } - var typeIdString = type.id.toString(); - if (visitedTypes.has(typeIdString)) { + if (visitedTypes[type.id]) { return; } - visitedTypes.set(typeIdString, type); + visitedTypes[type.id] = type; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; @@ -18585,23 +18791,15 @@ var ts; visitIndexedAccessType(type); } } - function visitTypeList(types) { - if (!types) { - return; - } - for (var i = 0; i < types.length; i++) { - visitType(types[i]); - } - } function visitTypeReference(type) { visitType(type.target); - visitTypeList(type.typeArguments); + ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { visitType(getConstraintFromTypeParameter(type)); } function visitUnionOrIntersectionType(type) { - visitTypeList(type.types); + ts.forEach(type.types, visitType); } function visitIndexType(type) { visitType(type.type); @@ -18621,7 +18819,7 @@ var ts; if (signature.typePredicate) { visitType(signature.typePredicate.type); } - visitTypeList(signature.typeParameters); + ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; visitSymbol(parameter); @@ -18631,8 +18829,8 @@ var ts; } function visitInterfaceType(interfaceT) { visitObjectType(interfaceT); - visitTypeList(interfaceT.typeParameters); - visitTypeList(getBaseTypes(interfaceT)); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); visitType(interfaceT.thisType); } function visitObjectType(type) { @@ -18658,11 +18856,11 @@ var ts; if (!symbol) { return; } - var symbolIdString = ts.getSymbolId(symbol).toString(); - if (visitedSymbols.has(symbolIdString)) { + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { return; } - visitedSymbols.set(symbolIdString, symbol); + visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { return true; } @@ -18710,7 +18908,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -18813,12 +19011,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -19115,7 +19313,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -19277,31 +19475,40 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -19344,9 +19551,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); @@ -19527,6 +19745,7 @@ var ts; var enumCount = 0; var symbolInstantiationDepth = 0; var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -19679,12 +19898,13 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + isArrayLikeType: isArrayLikeType, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; @@ -19763,7 +19983,8 @@ var ts; var deferredUnusedIdentifierNodes; var flowLoopStart = 0; var flowLoopCount = 0; - var visitedFlowCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); var resolutionTargets = []; @@ -19778,8 +19999,8 @@ var ts; var flowLoopNodes = []; var flowLoopKeys = []; var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; @@ -19908,6 +20129,7 @@ var ts; })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; function getJsxNamespace() { @@ -19989,7 +20211,7 @@ var ts; } function cloneSymbol(symbol) { var result = createSymbol(symbol.flags, symbol.escapedName); - result.declarations = symbol.declarations.slice(0); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -20217,10 +20439,10 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -20376,10 +20598,16 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 265); + if (lastLocation.commonJsModuleIndicator && name === "exports") { + return lastLocation.symbol; + } + } result = lookup(globals, name, meaning); } if (!result) { @@ -20491,7 +20719,7 @@ var ts; } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -20515,7 +20743,7 @@ var ts; error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -20525,14 +20753,14 @@ var ts; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -20560,11 +20788,17 @@ var ts; return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { + switch (node.kind) { + case 237: return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); + case 239: + return node.parent; + case 240: + return node.parent.parent; + case 242: + return node.parent.parent.parent; + default: + return undefined; } } function getDeclarationOfAliasSymbol(symbol) { @@ -20774,7 +21008,7 @@ var ts; var symbol; if (name.kind === 71) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, true); if (!symbol) { return undefined; } @@ -20813,7 +21047,7 @@ var ts; undefined; } else { - ts.Debug.fail("Unknown entity name kind."); + ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -20861,13 +21095,13 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -20966,10 +21200,9 @@ var ts; moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 && ts.pushIfUnique(visitedSymbols, symbol))) { return; } - visitedSymbols.push(symbol); var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports.get("__export"); if (exportStars) { @@ -21108,55 +21341,51 @@ var ts; return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { + var visitedSymbolTables = []; + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - visitedSymbolTables.push(symbols); var result = trySymbolTable(symbols); visitedSymbolTables.pop(); return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + function isUMDExportSymbol(symbol) { + return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.escapedName))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 - && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) + && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; } - }); - } - } - if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { @@ -21259,14 +21488,7 @@ var ts; isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } @@ -21288,7 +21510,7 @@ var ts; meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), @@ -21321,7 +21543,7 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(3, typeNode, sourceFile, writer); + printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; if (maxLength && result.length >= maxLength) { @@ -21603,13 +21825,13 @@ var ts; var i = 0; var qualifiedName = void 0; if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); @@ -21862,29 +22084,6 @@ var ts; } } } - function getNameOfSymbol(symbol, context) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return ts.unescapeLeadingUnderscores(symbol.escapedName); - } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { return ts.usingSingleLineStringWriter(function (writer) { @@ -21942,9 +22141,9 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol) { + function getNameOfSymbol(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -21954,6 +22153,9 @@ var ts; if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); } + if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } switch (declaration.kind) { case 199: return "(Anonymous class)"; @@ -21962,6 +22164,12 @@ var ts; return "(Anonymous function)"; } } + if (symbol.syntheticLiteralTypeOrigin) { + var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { + return "\"" + ts.escapeString(stringValue, 34) + "\""; + } + } return ts.unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder() { @@ -22158,13 +22366,13 @@ var ts; var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { - var length_3 = outerTypeParameters.length; - while (i < length_3) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { writeSymbolTypeReference(parent, typeArguments, start, i, flags); writePunctuation(writer, 23); @@ -22682,7 +22890,7 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); } else if (node.parent.kind === 246) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); @@ -22696,13 +22904,11 @@ var ts; ts.forEach(declarations, function (declaration) { getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } + ts.pushIfUnique(result, resultNode); if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -22713,8 +22919,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_4 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_4; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -23325,34 +23531,48 @@ var ts; for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } + typeParameters = ts.appendIfUnique(typeParameters, tp); } return typeParameters; } - function appendOuterTypeParameters(typeParameters, node) { + function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; if (!node) { - return typeParameters; + return undefined; } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } + switch (node.kind) { + case 229: + case 199: + case 230: + case 155: + case 156: + case 150: + case 160: + case 161: + case 273: + case 228: + case 151: + case 186: + case 187: + case 231: + case 282: + case 172: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 172) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var thisType = includeThisTypes && + (node.kind === 229 || node.kind === 199 || node.kind === 230) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); + return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; @@ -23400,7 +23620,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -23474,7 +23694,7 @@ var ts; var valueDecl = type.symbol.valueDeclaration; if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { + if (augTag && augTag.typeExpression && augTag.typeExpression.type) { baseType = getTypeFromTypeNode(augTag.typeExpression.type); } } @@ -23590,7 +23810,8 @@ var ts; var declaration = ts.find(symbol.declarations, function (d) { return d.kind === 283 || d.kind === 231; }); - var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -23924,7 +24145,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -23958,9 +24179,7 @@ var ts; if (!match) { return undefined; } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } + result = ts.appendIfUnique(result, match); } return result; } @@ -24136,7 +24355,11 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { + function addMemberForKeyType(t, propertySymbolOrIndex) { + var propertySymbol; + if (typeof propertySymbolOrIndex === "object") { + propertySymbol = propertySymbolOrIndex; + } var iterationMapper = createTypeMapper([typeParameter], [t]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); @@ -24151,6 +24374,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } + prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } else if (t.flags & 2) { @@ -24261,26 +24485,22 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getAllPossiblePropertiesOfType(type) { - if (type.flags & 65536) { - var props = ts.createSymbolTable(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var memberType = _a[_i]; - if (memberType.flags & 8190) { - continue; - } - for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { - var escapedName = _c[_b].escapedName; - if (!props.has(escapedName)) { - props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); - } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 65536)) { + return getPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var memberType = types_2[_i]; + for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); } } - return ts.arrayFrom(props.values()); - } - else { - return getPropertiesOfType(type); } + return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : @@ -24342,8 +24562,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type_2 = types_2[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type_2 = types_3[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -24406,20 +24626,15 @@ var ts; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var current = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var current = types_4[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } + props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | (!(modifiers & 24) ? 64 : 0) | (modifiers & 16 ? 128 : 0) | @@ -24545,12 +24760,7 @@ var ts; var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - if (!result) { - result = []; - } - result.push(tp); - } + result = ts.appendIfUnique(result, tp); }); return result; } @@ -24586,7 +24796,7 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512); return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { @@ -24636,11 +24846,10 @@ var ts; } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { if (!typeArguments) { typeArguments = []; @@ -24672,7 +24881,7 @@ var ts; var param = declaration.parameters[i]; var paramSymbol = param.symbol; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -24860,8 +25069,8 @@ var ts; } return anyType; } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -24874,12 +25083,20 @@ var ts; return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { @@ -24945,12 +25162,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_5 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_5) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_5 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -24967,8 +25184,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25004,13 +25221,14 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var isJavascript = ts.isInJavaScriptFile(node); + if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25026,7 +25244,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); } return instantiation; } @@ -25218,7 +25436,7 @@ var ts; return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); + return resolveName(undefined, name, meaning, diagnostic, name, false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -25364,6 +25582,20 @@ var ts; function containsType(types, type) { return binarySearchTypes(types, type) >= 0; } + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6368 && combined & 6368) { + return true; + } + combined |= t.flags; + if (combined & 6144 && combined & (32768 | 16777216)) { + return true; + } + } + return false; + } function addTypeToUnion(typeSet, type) { var flags = type.flags; if (flags & 65536) { @@ -25380,7 +25612,7 @@ var ts; if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192)) { + else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { if (flags & 2) typeSet.containsString = true; if (flags & 4) @@ -25398,14 +25630,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -25413,8 +25645,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -25538,8 +25770,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; addTypeToIntersection(typeSet, type); } } @@ -25685,20 +25917,6 @@ var ts; } return anyType; } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - if (accessNode) { - if (!isTypeAssignableTo(indexType, getIndexType(type))) { - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); - return unknownType; - } - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { - error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - } - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } function isGenericObjectType(type) { return type.flags & 540672 ? true : getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : @@ -25738,12 +25956,15 @@ var ts; getIntersectionType(stringIndexTypes) ]); } + if (isGenericMappedType(objectType)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; @@ -25756,7 +25977,7 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + if (indexType.flags & 65536 && !(indexType.flags & 8)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -25832,7 +26053,10 @@ var ts; return mapType(right, function (t) { return getSpreadType(left, t); }); } if (right.flags & 16777216) { - return emptyObjectType; + return nonPrimitiveType; + } + if (right.flags & (136 | 84 | 262178 | 272)) { + return left; } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); @@ -26052,10 +26276,6 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } function makeUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -26074,19 +26294,15 @@ var ts; } function createTypeMapper(sources, targets) { ts.Debug.assert(targets === undefined || sources.length === targets.length); - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; } function createTypeEraser(sources) { return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; + return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -26096,18 +26312,11 @@ var ts; createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } - function identityMapper(type) { - return type; - } function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; + return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; + return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { var result = createType(16384); @@ -26165,15 +26374,50 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } + if (symbol.isRestParameter) { + result.isRestParameter = symbol.isRestParameter; + } return result; } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (!typeParameters) { + var declaration_1 = symbol.declarations[0]; + var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + outerTypeParameters; + links.typeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + var combinedMapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function isTypeParameterReferencedWithin(tp, node) { + return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); + function checkThis(node) { + return node.kind === 169 || ts.forEachChild(node, checkThis); + } + function checkIdentifier(node) { + return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + } } function instantiateMappedType(type, mapper) { var constraintType = getConstraintTypeFromMappedType(type); @@ -26184,134 +26428,58 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); } return t; }); } } } - return instantiateMappedObjectType(type, mapper); + return instantiateAnonymousType(type, mapper); } function isMappableType(type) { return type.flags & (16384 | 32768 | 131072 | 524288); } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64, type.symbol); + if (type.objectFlags & 32) { + result.declaration = type.declaration; + } + result.target = type; + result.mapper = mapper; result.aliasSymbol = type.aliasSymbol; result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var d = typeParameters_1[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 273: - var func = node; - for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { - var p = _b[_a]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (type.objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } - return type; } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } - } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } return type; } @@ -26323,6 +26491,7 @@ var ts; switch (node.kind) { case 186: case 187: + case 151: return isContextSensitiveFunctionLikeDeclaration(node); case 178: return ts.forEach(node.properties, isContextSensitive); @@ -26336,9 +26505,6 @@ var ts; (isContextSensitive(node.left) || isContextSensitive(node.right)); case 261: return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); case 185: return isContextSensitive(node.expression); case 254: @@ -26425,7 +26591,8 @@ var ts; if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0; } - if (source.typeParameters) { + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; @@ -26668,6 +26835,13 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0; var overflow = false; var isIntersectionConstituent = false; @@ -26851,10 +27025,21 @@ var ts; } else { var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { - errorNode = prop.valueDeclaration; + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + if (ts.isIdentifier(propDeclaration.name)) { + suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } return { value: true }; @@ -27061,7 +27246,7 @@ var ts; } } else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); + var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { errorInfo = saveErrorInfo; @@ -27094,7 +27279,7 @@ var ts; } } else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); + var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { errorInfo = saveErrorInfo; @@ -27169,22 +27354,21 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + } + return 0; + } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 16777216) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 4194304)) { + if (!(targetProp.flags & 4194304)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { @@ -27456,9 +27640,10 @@ var ts; return type.flags & 16384 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } - function getTypeReferenceId(type, typeParameters) { + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } var result = "" + type.target.id; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; @@ -27470,6 +27655,9 @@ var ts; } result += "=" + index; } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } else { result += "-" + t.id; } @@ -27635,8 +27823,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -27672,7 +27860,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; + return !!(type.flags & 6368); } function isLiteralType(type) { return type.flags & 8 ? true : @@ -27700,8 +27888,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -27913,7 +28101,6 @@ var ts; function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; - context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -27951,7 +28138,7 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || + return !!(type.flags & (540672 | 262144) || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || @@ -28005,18 +28192,18 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } - function isPossiblyAssignableTo(source, target) { + function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (!(targetProp.flags & (16777216 | 4194304))) { - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (requireOptionalProperties || !(targetProp.flags & 16777216)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return false; + return targetProp; } } } - return true; + return undefined; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } @@ -28092,6 +28279,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 262144 && target.flags & 262144) { + inferFromTypes(source.type, target.type); + } + else if (source.flags & 524288 && target.flags & 524288) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (target.flags & 196608) { var targetTypes = target.types; var typeVariableCount = 0; @@ -28113,7 +28307,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 196608) { + else if (source.flags & 65536) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -28122,7 +28316,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 32768) { + if (source.flags & (32768 | 131072)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -28157,6 +28351,10 @@ var ts; return undefined; } function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } if (getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); if (constraintType.flags & 262144) { @@ -28178,7 +28376,7 @@ var ts; return; } } - if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0); inferFromSignatures(source, target, 1); @@ -28189,7 +28387,7 @@ var ts; var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -28235,8 +28433,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28307,7 +28505,8 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -28471,8 +28670,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -28729,8 +28928,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -28799,8 +28998,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -28849,69 +29048,87 @@ var ts; } return false; } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return unknownType; + } if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } - var visitedFlowStart = visitedFlowCount; + var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; + sharedFlowCount = sharedFlowStart; var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { + if (flowDepth === 2500) { + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return unknownType; + } + flowDepth++; while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; + var flags = flow.flags; + if (flags & 1024) { + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; } } } var type = void 0; - if (flow.flags & 4096) { + if (flags & 4096) { flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flow.flags & 2048) { + else if (flags & 2048) { flow = flow.antecedent; continue; } - else if (flow.flags & 16) { + else if (flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 96) { + else if (flags & 96) { type = getTypeAtFlowCondition(flow); } - else if (flow.flags & 128) { + else if (flags & 128) { type = getTypeAtSwitchClause(flow); } - else if (flow.flags & 12) { + else if (flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flow.flags & 4 ? + type = flags & 4 ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flow.flags & 256) { + else if (flags & 256) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 2) { + else if (flags & 2) { var container = flow.container; if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { flow = container.flowNode; @@ -28922,11 +29139,12 @@ var ts; else { type = convertAutoToAny(declaredType); } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; + if (flags & 1024) { + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; } + flowDepth--; return type; } } @@ -28955,30 +29173,32 @@ var ts; return undefined; } function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 84)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + return flowType; } - return flowType; } return undefined; } @@ -29024,9 +29244,7 @@ var ts; if (type === declaredType && declaredType === initialType) { return type; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -29073,9 +29291,7 @@ var ts; if (cached_1) { return cached_1; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -29849,7 +30065,8 @@ var ts; } } } - if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var inJs = ts.isInJavaScriptFile(func); + if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { var contextualType = getApparentTypeOfContextualType(containingLiteral); @@ -29868,10 +30085,18 @@ var ts; } return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; + var parent = func.parent; + if (parent.kind === 194 && parent.operatorToken.kind === 58) { + var target = parent.left; if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); + var expression = target.expression; + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); } } } @@ -30025,7 +30250,7 @@ var ts; else if (operator === 54) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left, true); } return type; } @@ -30071,16 +30296,10 @@ var ts; } return undefined; } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIndexTypeOfContextualType(arrayContextualType, 1) + || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); } function getContextualTypeForConditionalOperand(node) { var conditional = node.parent; @@ -30154,15 +30373,20 @@ var ts; return getContextualTypeForObjectLiteralElement(parent); case 263: return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); + case 177: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } case 195: return getContextualTypeForConditionalOperand(node); case 205: ts.Debug.assert(parent.parent.kind === 196); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); + case 185: { + var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } case 256: return getContextualTypeForJsxExpression(parent); case 253: @@ -30225,8 +30449,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -30264,8 +30488,9 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elements.length; index++) { + var e = elements[index]; if (inDestructuringPattern && e.kind === 198) { var restArrayType = checkExpression(e.expression, checkMode); var restElementType = getIndexTypeOfType(restArrayType, 1) || @@ -30275,7 +30500,8 @@ var ts; } } else { - var type = checkExpressionForMutableLocation(e, checkMode); + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 198; @@ -30286,15 +30512,15 @@ var ts; type.pattern = node; return type; } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; + var contextualType_1 = getApparentTypeOfContextualType(node); + if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { + var pattern = contextualType_1.pattern; if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType_1.typeArguments[i]); } else { if (patternElement.kind !== 200) { @@ -30380,6 +30606,7 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = memberDecl.symbol; + var literalName = void 0; if (memberDecl.kind === 261 || memberDecl.kind === 262 || ts.isObjectLiteralMethod(memberDecl)) { @@ -30389,6 +30616,12 @@ var ts; } var type = void 0; if (memberDecl.kind === 261) { + if (memberDecl.name.kind === 144) { + var t = checkComputedPropertyName(memberDecl.name); + if (t.flags & 224) { + literalName = ts.escapeLeadingUnderscores("" + t.value); + } + } type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === 151) { @@ -30403,14 +30636,14 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.escapedName); + var prop = createSymbol(4 | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } @@ -30457,7 +30690,7 @@ var ts; ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); checkNodeDeferred(memberDecl); } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -30515,7 +30748,8 @@ var ts; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + return !!(type.flags & (1 | 16777216) || + getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || type.flags & 32768 && !isGenericMappedType(type) || type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } @@ -30705,8 +30939,9 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + var isJavascript = ts.isInJavaScriptFile(node); + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); @@ -30989,7 +31224,7 @@ var ts; checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = true; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -31165,19 +31400,8 @@ var ts; } return unknownType; } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - } - markPropertyAsReferenced(prop); + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -31196,6 +31420,56 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + else if (valueDeclaration.kind === 229 && + node.parent.kind !== 159 && + !ts.isInAmbientContext(valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 149: + return true; + case 261: + return false; + default: + return ts.isPartOfExpression(node) ? false : "quit"; + } + }); + } + function isPropertyDeclaredInAncestorClass(prop) { + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + ts.Debug.assert(x.length === 1); + return x[0]; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -31208,8 +31482,8 @@ var ts; } } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + if (suggestion !== undefined) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -31221,7 +31495,7 @@ var ts; return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { var symbol = getSymbol(symbols, name, meaning); if (symbol) { return symbol; @@ -31281,11 +31555,12 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) + && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -31294,15 +31569,6 @@ var ts; } } } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -31493,7 +31759,6 @@ var ts; var argCount; var typeArguments; var callIsIncomplete; - var isDecorator; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; @@ -31515,7 +31780,6 @@ var ts; } } else if (node.kind === 147) { - isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } @@ -31564,7 +31828,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } - return getSignatureInstantiation(signature, getInferredTypes(context)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -31573,13 +31837,13 @@ var ts; inference.inferredType = undefined; } } - if (ts.isExpression(node)) { + if (node.kind !== 147) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); @@ -31999,8 +32263,9 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { candidateForTypeArgumentError = originalCandidate; break; @@ -32009,7 +32274,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { candidateForArgumentError = candidate; @@ -32115,11 +32380,6 @@ var ts; if (expressionType === unknownType) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -32131,6 +32391,11 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } var callSignatures = getSignaturesOfType(expressionType, 0); @@ -32244,8 +32509,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32270,7 +32535,7 @@ var ts; case 250: return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); @@ -32284,16 +32549,30 @@ var ts; return result; } function isJavaScriptConstructor(node) { - if (ts.isInJavaScriptFile(node)) { + if (node && ts.isInJavaScriptFile(node)) { if (ts.getJSDocClassTag(node)) return true; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; return symbol && symbol.members !== undefined; } return false; } + function getJavaScriptClassType(symbol) { + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + } + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + return getInferredClassType(symbol); + } + if (symbol.flags & 3) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + return getInferredClassType(valueType.symbol); + } + } + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -32322,13 +32601,11 @@ var ts; var funcSymbol = node.expression.kind === 71 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { - return getInferredClassType(funcSymbol); + var type = funcSymbol && getJavaScriptClassType(funcSymbol); + if (type) { + return type; } - else if (noImplicitAny) { + if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -32389,7 +32666,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); if (!resolvedRequire) { return true; } @@ -32495,7 +32772,7 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } @@ -32625,9 +32902,7 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } }); return aggregatedTypes; @@ -32671,9 +32946,7 @@ var ts; if (type.flags & 8192) { hasReturnOfTypeNever = true; } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } else { hasReturnWithNoExpression = true; @@ -32684,9 +32957,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } + ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } @@ -32939,8 +33210,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33438,20 +33709,6 @@ var ts; var type2 = checkExpression(node.whenFalse, checkMode); return getBestChoiceType(type1, type2); } - function checkLiteralExpression(node) { - switch (node.kind) { - case 13: - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - checkGrammarNumericLiteral(node); - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); @@ -33503,9 +33760,13 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode) { + function checkExpressionForMutableLocation(node, checkMode, contextualType) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); + return shouldWiden ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, checkMode) { if (node.name.kind === 144) { @@ -33573,12 +33834,9 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); - if (typecasts && typecasts.length) { - var cast_1 = typecasts[0]; - return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); - } + var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } @@ -33594,10 +33852,14 @@ var ts; return nullWideningType; case 13: case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: + return trueType; case 86: - return checkLiteralExpression(node); + return falseType; case 196: return checkTemplateExpression(node); case 12: @@ -34146,7 +34408,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, ts.isInJavaScriptFile(typeArgumentNodes[i])); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -34214,6 +34476,10 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } return type; } if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { @@ -34479,6 +34745,7 @@ var ts; switch (d.kind) { case 230: case 231: + case 283: return 2; case 233: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 @@ -34488,6 +34755,8 @@ var ts; case 232: return 2 | 1; case 237: + case 240: + case 239: var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); @@ -34677,8 +34946,11 @@ var ts; markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } function markEntityNameOrEntityExpressionAsReference(typeName) { - var rootName = typeName && getFirstIdentifier(typeName); - var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 && symbolIsValue(rootSymbol) @@ -34784,22 +35056,12 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDoc(node) { - if (!ts.isInJavaScriptFile(node)) { - return; - } - ts.forEach(node.jsDoc, checkSourceElement); - } - function checkJSDocComment(node) { - if (node.tags) { - for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - checkSourceElement(tag); - } + function checkJSDocTypedefTag(node) { + if (!node.typeExpression) { + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } function checkFunctionOrMethodDeclaration(node) { - checkJSDoc(node); checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); @@ -34904,11 +35166,11 @@ var ts; !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); } } }); @@ -34921,15 +35183,17 @@ var ts; } return false; } - function errorUnusedLocal(node, name) { + function errorUnusedLocal(declaration, name) { + var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + var declaration_2 = ts.getRootDeclaration(node.parent); + if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 145) { return; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } function parameterNameStartsWithUnderscore(parameterName) { @@ -34945,14 +35209,14 @@ var ts; var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -34970,8 +35234,8 @@ var ts; } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -34984,7 +35248,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); } } } @@ -34995,7 +35259,14 @@ var ts; if (node.kind === 207) { checkGrammarStatementInAmbientContext(node); } - ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } if (node.locals) { registerForUnusedIdentifiersCheck(node); } @@ -35125,7 +35396,7 @@ var ts; if (symbol.flags & 1) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { @@ -35161,7 +35432,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -35222,7 +35493,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); + markPropertyAsReferenced(property, undefined); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -36627,8 +36898,8 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } } @@ -36655,7 +36926,7 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768); } } @@ -36672,7 +36943,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); } @@ -36705,9 +36976,12 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); + if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -36737,7 +37011,7 @@ var ts; if (flags & (1920 | 64 | 384)) { return; } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); if (flags & 524288 && exportedDeclarationsCount <= 2) { return; } @@ -36752,15 +37026,24 @@ var ts; }); links.exportsChecked = true; } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } + } + function isNotAccessor(declaration) { + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var tags = _a[_i].tags; + ts.forEach(tags, checkSourceElement); + } + } var kind = node.kind; if (cancellationToken) { switch (kind) { @@ -36812,8 +37095,8 @@ var ts; case 168: case 170: return checkSourceElement(node.type); - case 275: - return checkJSDocComment(node); + case 283: + return checkJSDocTypedefTag(node); case 279: return checkSourceElement(node.typeExpression); case 273: @@ -36943,6 +37226,7 @@ var ts; ts.clear(potentialNewTargetCollisions); deferredNodes = []; deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalModule(node)) { @@ -37272,11 +37556,13 @@ var ts; return sig.thisParameter; } } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } case 169: - return getTypeFromTypeNode(node).symbol; + return getTypeFromThisTypeNode(node).symbol; + case 97: + return checkExpression(node).symbol; case 123: var constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === 152) { @@ -37290,13 +37576,17 @@ var ts; return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - return getPropertyOfType(objectType, node.text); - } - break; + var objectType = ts.isElementAccessExpression(node.parent) + ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined + : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) + ? getTypeFromTypeNode(node.parent.parent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 79: + return getSymbolOfNode(node.parent); + default: + return undefined; } - return undefined; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 262) { @@ -37407,9 +37697,9 @@ var ts; function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { var symbols_4 = []; - var name_2 = symbol.escapedName; + var name_3 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_2); + var symbol = getPropertyOfType(t, name_3); if (symbol) { symbols_4.push(symbol); } @@ -37510,7 +37800,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + if (resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -37653,6 +37943,14 @@ var ts; return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { @@ -37736,7 +38034,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -38012,7 +38310,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -38034,12 +38332,6 @@ var ts; case 113: case 112: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } @@ -38531,7 +38823,7 @@ var ts; currentKind = SetAccessor; } else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -38791,7 +39083,7 @@ var ts; } } } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { checkESModuleMarker(node.name); } @@ -38806,8 +39098,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; if (!ts.isOmittedExpression(element)) { return checkESModuleMarker(element.name); } @@ -38822,8 +39114,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -39272,7 +39564,7 @@ var ts; || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node) + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } ts.updateParameter = updateParameter; @@ -39888,13 +40180,26 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanTokenOrBody, bodyOrUndefined) { + var equalsGreaterThanToken; + var body; + if (bodyOrUndefined === undefined) { + equalsGreaterThanToken = node.equalsGreaterThanToken; + body = ts.cast(equalsGreaterThanTokenOrBody, ts.isConciseBody); + } + else { + equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { + return n.kind === 36; + }); + body = bodyOrUndefined; + } return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node) + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } ts.updateArrowFunction = updateArrowFunction; @@ -39999,11 +40304,23 @@ var ts; return node; } ts.createConditional = createConditional; - function updateConditional(node, condition, whenTrue, whenFalse) { + function updateConditional(node, condition) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (args.length === 2) { + var whenTrue_1 = args[0], whenFalse_1 = args[1]; + return updateConditional(node, condition, node.questionToken, whenTrue_1, node.colonToken, whenFalse_1); + } + ts.Debug.assert(args.length === 4); + var questionToken = args[0], whenTrue = args[1], colonToken = args[2], whenFalse = args[3]; return node.condition !== condition + || node.questionToken !== questionToken || node.whenTrue !== whenTrue + || node.colonToken !== colonToken || node.whenFalse !== whenFalse - ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node) + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } ts.updateConditional = updateConditional; @@ -40021,6 +40338,30 @@ var ts; : node; } ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(14); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(15); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(16); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(13); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { var node = createSynthesizedNode(197); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; @@ -41108,6 +41449,10 @@ var ts; return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction(undefined, undefined, param ? [param] : [], undefined, undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { return createBinary(left, 26, right); } @@ -41303,9 +41648,7 @@ var ts; var emitNode = getOrCreateEmitNode(node); for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { var helper = helpers_1[_i]; - if (!ts.contains(emitNode.helpers, helper)) { - emitNode.helpers = ts.append(emitNode.helpers, helper); - } + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); } } return node; @@ -41338,9 +41681,7 @@ var ts; var helper = sourceEmitHelpers[i]; if (predicate(helper)) { helpersRemoved++; - if (!ts.contains(targetEmitNode.helpers, helper)) { - targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); - } + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); } else if (helpersRemoved > 0) { sourceEmitHelpers[i - helpersRemoved] = helper; @@ -42058,11 +42399,9 @@ var ts; return recreateOuterExpressions(expression, mutableCall, 4); } } - else { - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { - return ts.setTextRange(ts.createParen(expression), expression); - } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + return ts.setTextRange(ts.createParen(expression), expression); } return expression; } @@ -42198,9 +42537,17 @@ var ts; case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } + function isIgnorableParen(node) { + return node.kind === 185 + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { if (kinds === void 0) { kinds = 7; } - if (outerExpression && isOuterExpression(outerExpression, kinds)) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; @@ -42226,7 +42573,8 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var create = hasExportStarsToExportValues && moduleKind !== ts.ModuleKind.System - && moduleKind !== ts.ModuleKind.ES2015; + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; if (!create) { var helpers = ts.getEmitHelpers(node); if (helpers) { @@ -42656,7 +43004,7 @@ var ts; case 186: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -42672,7 +43020,7 @@ var ts; case 194: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 197: @@ -43426,7 +43774,7 @@ var ts; } else { var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); exportedNames = ts.append(exportedNames, name); @@ -43719,7 +44067,7 @@ var ts; } function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -43902,6 +44250,21 @@ var ts; return saveStateAndInvoke(node, sourceElementVisitorWorker); } function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 238: + case 237: + case 243: + case 244: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + return node; + } switch (node.kind) { case 238: return visitImportDeclaration(node); @@ -43912,7 +44275,7 @@ var ts; case 244: return visitExportDeclaration(node); default: - return visitorWorker(node); + ts.Debug.fail("Unhandled ellided statement"); } } function namespaceElementVisitor(node) { @@ -44062,7 +44425,7 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && - !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { @@ -44126,8 +44489,10 @@ var ts; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -44733,7 +45098,7 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8; name.original = undefined; - name.parent = currentScope; + name.parent = ts.getParseTreeNode(currentScope); if (useFallback) { return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } @@ -44863,7 +45228,7 @@ var ts; return updated; } function visitArrowFunction(node) { - var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } function visitParameter(node) { @@ -44999,6 +45364,7 @@ var ts; return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { @@ -45458,7 +45824,6 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var currentSourceFile; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var previousOnEmitNode = context.onEmitNode; @@ -45470,10 +45835,8 @@ var ts; if (node.isDeclarationFile) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -45516,7 +45879,7 @@ var ts; : ts.visitFunctionBody(node.body, visitor, context)); } function visitArrowFunction(node) { - return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -45806,8 +46169,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { - var e = elements_4[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; if (e.kind === 263) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -45825,7 +46188,7 @@ var ts; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } else { - chunkObject.push(e); + chunkObject.push(ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } } } @@ -46015,7 +46378,7 @@ var ts; function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } @@ -46840,58 +47203,12 @@ var ts; && node.kind === 219 && !node.expression; } - function isClassLikeVariableStatement(node) { - if (!ts.isVariableStatement(node)) - return false; - var variable = ts.singleOrUndefined(node.declarationList.declarations); - return variable - && variable.initializer - && ts.isIdentifier(variable.name) - && (ts.isClassLike(variable.initializer) - || (ts.isAssignmentExpression(variable.initializer) - && ts.isIdentifier(variable.initializer.left) - && ts.isClassLike(variable.initializer.right))); - } - function isTypeScriptClassWrapper(node) { - var call = ts.tryCast(node, ts.isCallExpression); - if (!call || ts.isParseTreeNode(call) || - ts.some(call.typeArguments) || - ts.some(call.arguments)) { - return false; - } - var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); - if (!func || ts.isParseTreeNode(func) || - ts.some(func.typeParameters) || - ts.some(func.parameters) || - func.type || - !func.body) { - return false; - } - var statements = func.body.statements; - if (statements.length < 2) { - return false; - } - var firstStatement = statements[0]; - if (ts.isParseTreeNode(firstStatement) || - !ts.isClassLike(firstStatement) && - !isClassLikeVariableStatement(firstStatement)) { - return false; - } - var lastStatement = ts.elementAt(statements, -1); - var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); - if (!returnStatement || - !returnStatement.expression || - !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { - return false; - } - return true; - } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) - || isTypeScriptClassWrapper(node); + || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -48371,7 +48688,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (isTypeScriptClassWrapper(node)) { + if (ts.getEmitFlags(node) & 33554432) { return visitTypeScriptClassWrapper(node); } if (node.transformFlags & 64) { @@ -48380,7 +48697,7 @@ var ts; return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } function visitTypeScriptClassWrapper(node) { - var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); @@ -48870,7 +49187,6 @@ var ts; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; var renamedCatchVariables; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; @@ -48901,10 +49217,8 @@ var ts; if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -50578,6 +50892,7 @@ var ts; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var umdHeader = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(ts.createBlock([ ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ ts.createVariableStatement(undefined, [ @@ -50588,13 +50903,13 @@ var ts; ]), ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, [ + ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), ts.createIdentifier("factory") - ])) + ]))) ]))) ], true), undefined)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ @@ -50659,17 +50974,20 @@ var ts; } function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - if (emitAsReturn) { - var statement = ts.createReturn(currentModuleInfo.exportEquals.expression); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 | 1536); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression)); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536); - statements.push(statement); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); + statements.push(statement); + } } } } @@ -51003,7 +51321,7 @@ var ts; return statements; } if (ts.hasModifier(decl, 1)) { - var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); } if (decl.name) { @@ -51712,7 +52030,8 @@ var ts; } function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - return ts.createCall(exportFunction, undefined, [exportName, value]); + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536); + return ts.setCommentRange(ts.createCall(exportFunction, undefined, [exportName, value]), value); } function nestedElementVisitor(node) { switch (node.kind) { @@ -54843,8 +55162,13 @@ var ts; comments.reset(); setWriter(undefined); } + function emitIfPresent(node) { + if (node) { + emit(node); + } + } function emit(node) { - pipelineEmitWithNotification(3, node); + pipelineEmitWithNotification(4, node); } function emitIdentifierName(node) { pipelineEmitWithNotification(2, node); @@ -54882,7 +55206,8 @@ var ts; case 0: return pipelineEmitSourceFile(node); case 2: return pipelineEmitIdentifierName(node); case 1: return pipelineEmitExpression(node); - case 3: return pipelineEmitUnspecified(node); + case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -54893,6 +55218,11 @@ var ts; ts.Debug.assertNode(node, ts.isIdentifier); emitIdentifier(node); } + function emitMappedTypeParameter(node) { + emit(node.name); + write(" in "); + emit(node.constraint); + } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { @@ -55236,9 +55566,9 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -55250,7 +55580,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); write(";"); } @@ -55258,7 +55588,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -55267,7 +55597,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); @@ -55276,9 +55606,9 @@ var ts; function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.asteriskToken, "*"); + emitIfPresent(node.asteriskToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -55348,9 +55678,8 @@ var ts; } function emitTypeLiteral(node) { write("{"); - if (node.members.length > 0) { - emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); - } + var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; + emitList(node, node.members, flags | 262144); write("}"); } function emitArrayType(node) { @@ -55397,13 +55726,14 @@ var ts; writeLine(); increaseIndent(); } - writeIfPresent(node.readonlyToken, "readonly "); + if (node.readonlyToken) { + emit(node.readonlyToken); + write(" "); + } write("["); - emit(node.typeParameter.name); - write(" in "); - emit(node.typeParameter.constraint); + pipelineEmitWithNotification(3, node.typeParameter); write("]"); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); @@ -55443,36 +55773,25 @@ var ts; } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - var preferNewLine = node.multiLine ? 32768 : 0; - emitExpressionList(node, elements, 4466 | preferNewLine); - } + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); } function emitObjectLiteralExpression(node) { - var properties = node.properties; - if (properties.length === 0) { - write("{}"); + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); } - else { - var indentedFlag = ts.getEmitFlags(node) & 65536; - if (indentedFlag) { - increaseIndent(); - } - var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; - emitList(node, properties, 978 | allowTrailingComma | preferNewLine); - if (indentedFlag) { - decreaseIndent(); - } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; + emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); } } function emitPropertyAccessExpression(node) { @@ -55554,7 +55873,8 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); emitWithPrefix(": ", node.type); - write(" =>"); + write(" "); + emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { write("delete "); @@ -55609,12 +55929,12 @@ var ts; var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); increaseIndentIf(indentBeforeQuestion, " "); - write("?"); + emit(node.questionToken); increaseIndentIf(indentAfterQuestion, " "); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); increaseIndentIf(indentBeforeColon, " "); - write(":"); + emit(node.colonToken); increaseIndentIf(indentAfterColon, " "); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); @@ -55624,7 +55944,8 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write(node.asteriskToken ? "yield*" : "yield"); + write("yield"); + emit(node.asteriskToken); emitExpressionWithPrefix(" ", node.expression); } function emitSpreadExpression(node) { @@ -55659,27 +55980,16 @@ var ts; emit(node.literal); } function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - writeToken(17, node.pos, node); - write(" "); - writeToken(18, node.statements.end, node); - } - else { - writeToken(17, node.pos, node); - emitBlockStatements(node); - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18, node.statements.end, node); - } + writeToken(17, node.pos, node); + emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); + writeToken(18, node.statements.end, node); } - function emitBlockStatements(node) { - if (ts.getEmitFlags(node) & 1) { - emitList(node, node.statements, 384); - } - else { - emitList(node, node.statements, 65); - } + function emitBlockStatements(node, forceSingleLine) { + var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; + emitList(node, node.statements, format); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -55857,7 +56167,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.asteriskToken ? "function* " : "function "); + write("function"); + emitIfPresent(node.asteriskToken); + write(" "); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55875,7 +56187,7 @@ var ts; if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -55885,7 +56197,7 @@ var ts; pushNameGenerationScope(); emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -56023,7 +56335,9 @@ var ts; } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - write(node.flags & 16 ? "namespace " : "module "); + if (~node.flags & 512) { + write(node.flags & 16 ? "namespace " : "module "); + } emit(node.name); var body = node.body; while (body.kind === 233) { @@ -56035,16 +56349,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isEmptyBlock(node)) { - write("{ }"); - } - else { - pushNameGenerationScope(); - write("{"); - emitBlockStatements(node); - write("}"); - popNameGenerationScope(); - } + pushNameGenerationScope(); + write("{"); + emitBlockStatements(node, isEmptyBlock(node)); + write("}"); + popNameGenerationScope(); } function emitCaseBlock(node) { writeToken(17, node.pos); @@ -56187,9 +56496,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { write("{"); - if (node.dotDotDotToken) { - write("..."); - } + emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); write("}"); } @@ -56220,13 +56527,12 @@ var ts; if (statements.length > 0) { emitTrailingCommentsOfPosition(statements.pos); } + var format = 81985; if (emitAsSingleStatement) { write(" "); - emit(statements[0]); - } - else { - emitList(parentNode, statements, 81985); + format &= ~(1 | 64); } + emitList(parentNode, statements, format); } function emitHeritageClause(node) { write(" "); @@ -56419,7 +56725,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emit(parameters[0]); + emitList(parentNode, parameters, 1360 & ~1024); } else { emitParameters(parentNode, parameters); @@ -56441,8 +56747,14 @@ var ts; if (isUndefined && format & 8192) { return; } - var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + var isEmpty = isUndefined || start >= children.length || count === 0; if (isEmpty && format & 16384) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } return; } if (format & 7680) { @@ -56455,7 +56767,7 @@ var ts; if (format & 1) { writeLine(); } - else if (format & 128) { + else if (format & 128 && !(format & 262144)) { write(" "); } } @@ -56514,7 +56826,7 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -56551,11 +56863,6 @@ var ts; write(text); } } - function writeIfPresent(node, text) { - if (node) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -56565,7 +56872,7 @@ var ts; if (onBeforeEmitToken) { onBeforeEmitToken(node); } - writeTokenText(node.kind); + write(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } @@ -56714,10 +57021,6 @@ var ts; && !ts.nodeIsSynthesized(node2) && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } - function isSingleLineEmptyBlock(block) { - return !block.multiLine - && isEmptyBlock(block); - } function isEmptyBlock(block) { return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); @@ -56961,6 +57264,8 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; @@ -56970,7 +57275,7 @@ var ts; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; @@ -57164,7 +57469,7 @@ var ts; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -57188,7 +57493,7 @@ var ts; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; + var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -57213,9 +57518,9 @@ var ts; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { - var start = diagnostic.start, length_6 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_6), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -57223,10 +57528,10 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += ts.sys.newLine; + output += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -57235,7 +57540,7 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; + output += lineContent + host.getNewLine(); output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; output += redForegroundEscapeSequence; if (i === firstLine) { @@ -57250,15 +57555,15 @@ var ts; output += lineContent.replace(/./g, "~"); } output += resetEscapeSequence; - output += ts.sys.newLine; + output += host.getNewLine(); } - output += ts.sys.newLine; + output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine; + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += host.getNewLine(); } return output; } @@ -57324,6 +57629,8 @@ var ts; ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); @@ -57373,12 +57680,11 @@ var ts; } if (!skipDefaultLib) { if (!options.lib) { - processRootFile(host.getDefaultLibFileName(options), true); + processRootFile(getDefaultLibraryFileName(), true); } else { - var libDirectory_1 = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(host.getDefaultLibFileName(options)); ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(libDirectory_1, libFileName), true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true); }); } } @@ -57411,6 +57717,7 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, @@ -57634,7 +57941,7 @@ var ts; var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -57701,6 +58008,15 @@ var ts; function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (defaultLibraryPath && defaultLibraryPath.length !== 0) { + return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + } + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } @@ -57815,9 +58131,7 @@ var ts; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - return ts.isSourceFileJavaScript(sourceFile) - ? ts.filter(diagnostics, shouldReportDiagnostic) - : diagnostics; + return ts.filter(diagnostics, shouldReportDiagnostic); }); } function shouldReportDiagnostic(diagnostic) { @@ -58033,16 +58347,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.text === b.text; - } - function getTextOfLiteral(literal) { - return literal.text; + return a.kind === 9 + ? b.kind === 9 && a.text === b.text + : b.kind === 71 && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -58158,8 +58471,8 @@ var ts; return sourceFileWithAddedExtension; } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { + function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -58225,7 +58538,7 @@ var ts; } }); if (packageId) { - var packageIdKey = packageId.name + "@" + packageId.version; + var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -58272,7 +58585,7 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -58294,7 +58607,7 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { if (previousResolution) { @@ -58307,7 +58620,7 @@ var ts; saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -58336,8 +58649,7 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); - var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); @@ -58348,13 +58660,19 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -58669,7 +58987,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -58677,6 +58995,17 @@ var ts; ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); return names; } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9) { + res.push(aug.text); + } + } + return res; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -59612,7 +59941,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; if (jsonConversionNotifier && (parentOption || knownOptions === knownRootOptions)) { @@ -59647,7 +59976,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); return null; case 9: if (!isDoubleQuotedString(valueExpression)) { @@ -59703,6 +60032,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; if (option.type === "list") { return ts.isArray(value); } @@ -59855,6 +60186,12 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } @@ -59878,7 +60215,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -59890,7 +60227,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -59899,7 +60236,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -59916,7 +60253,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -59978,7 +60315,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -60000,7 +60338,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -60154,6 +60493,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -60176,6 +60517,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -60212,7 +60555,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -60461,7 +60804,6 @@ var ts; var commandLine = ts.parseCommandLine(args); var configFileName; var cachedConfigFileText; - var configFileWatcher; var directoryWatcher; var cachedProgram; var rootFileNames; @@ -60536,7 +60878,7 @@ var ts; return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (configFileName) { - configFileWatcher = ts.sys.watchFile(configFileName, configFileChanged); + ts.sys.watchFile(configFileName, configFileChanged); } if (ts.sys.watchDirectory && configFileName) { var directory = ts.getDirectoryPath(configFileName); @@ -60750,15 +61092,15 @@ var ts; return { program: program, exitStatus: exitStatus }; function compileProgram() { var diagnostics; - diagnostics = program.getSyntacticDiagnostics(); + diagnostics = program.getSyntacticDiagnostics().slice(); if (diagnostics.length === 0) { diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); if (diagnostics.length === 0) { - diagnostics = program.getSemanticDiagnostics(); + diagnostics = program.getSemanticDiagnostics().slice(); } } var emitOutput = program.emit(); - diagnostics = diagnostics.concat(emitOutput.diagnostics); + ts.addRange(diagnostics, emitOutput.diagnostics); reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), compilerHost); reportEmittedFiles(emitOutput.emittedFiles); if (emitOutput.emitSkipped && diagnostics.length > 0) { diff --git a/lib/tsserver.js b/lib/tsserver.js index c18f6507caa22..cf8cbbea28146 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -705,6 +705,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; @@ -1065,6 +1066,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1097,7 +1099,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; @@ -1164,6 +1167,12 @@ var ts; ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; @@ -1795,6 +1804,26 @@ var ts; return to; } ts.addRange = addRange; + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; function stableSort(array, comparer) { if (comparer === void 0) { comparer = compareValues; } return array @@ -1941,6 +1970,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2105,6 +2144,8 @@ var ts; ts.cast = cast; function noop() { } ts.noop = noop; + function identity(x) { return x; } + ts.identity = identity; function notImplemented() { throw new Error("Not implemented"); } @@ -2181,12 +2222,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2428,12 +2468,8 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2470,7 +2506,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3096,6 +3132,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3233,6 +3273,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); var ts; (function (ts) { @@ -3797,8 +3843,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4118,7 +4164,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4191,6 +4239,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4308,7 +4357,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4413,17 +4462,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -4514,6 +4562,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4561,7 +4610,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); var ts; @@ -4591,7 +4640,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -4694,12 +4743,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -4996,7 +5045,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -5158,31 +5207,40 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -5225,9 +5283,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); @@ -5386,7 +5455,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -5410,15 +5478,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -5452,7 +5519,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -5574,7 +5641,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } if (node.kind === 286 && node._children.length > 0) { @@ -5611,6 +5678,15 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; + } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -5638,6 +5714,7 @@ var ts; case 16: return "}" + escapeText(node.text, 96) + "`"; case 8: + case 12: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -5735,6 +5812,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155: + case 156: + case 150: + case 157: + case 160: + case 161: + case 273: + case 229: + case 199: + case 230: + case 231: + case 282: + case 228: + case 151: + case 152: + case 153: + case 154: + case 186: + case 187: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -6382,59 +6487,62 @@ var ts; case 8: case 9: case 99: - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: - return parent.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: - return parent.expression === node; - case 214: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215: - case 216: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || - forInStatement.expression === node; - case 184: - case 202: - return node === parent.expression; - case 205: - return node === parent.expression; - case 144: - return node === parent.expression; - case 147: - case 256: - case 255: - case 263: - return true; - case 201: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -6598,14 +6706,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -6613,14 +6713,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -6652,22 +6744,17 @@ var ts; getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getParameterSymbolFromJSDoc(node) { if (node.symbol) { return node.symbol; @@ -6693,38 +6780,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -6736,7 +6791,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -7137,9 +7192,9 @@ var ts; || kind === 265; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -7403,13 +7458,17 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" }); + var escapedNullRegExp = /\\0[0-9]/g; function escapeString(s, quoteChar) { var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -7689,7 +7748,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -7698,7 +7757,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -7707,7 +7766,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -8266,6 +8325,41 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + AccessKind[AccessKind["Read"] = 0] = "Read"; + AccessKind[AccessKind["Write"] = 1] = "Write"; + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0; + switch (parent.kind) { + case 193: + case 192: + var operator = parent.operator; + return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; + case 194: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; + case 179: + return parent.name !== node ? 0 : accessKind(parent); + default: + return 0; + } + function writeOrReadWrite() { + return parent.parent && parent.parent.kind === 210 ? 1 : 2; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -8544,6 +8638,56 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 208: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210: + var expr = hostNode.expression; + switch (expr.kind) { + case 179: + return expr.name; + case 180: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1: + return undefined; + case 185: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -8563,11 +8707,78 @@ var ts; return undefined; } } + else if (declaration.kind === 283) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getJSDocTypeTag(node) { + var tag = getFirstJSDocTag(node, 281); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -9200,8 +9411,7 @@ var ts; } ts.isToken = isToken; function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; function isLiteralKind(kind) { @@ -9286,16 +9496,27 @@ var ts; return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152: - case 186: case 228: - case 187: case 151: - case 150: + case 152: case 153: case 154: + case 186: + case 187: + return true; + default: + return false; + } + } + function isFunctionLikeKind(kind) { + switch (kind) { + case 150: case 155: case 156: case 157: @@ -9303,10 +9524,15 @@ var ts; case 273: case 161: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; return kind === 152 @@ -9460,52 +9686,61 @@ var ts; || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 91 - || kind === 203 - || kind === 204; - } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179: + case 180: + case 182: + case 181: + case 249: + case 250: + case 183: + case 177: + case 185: + case 178: + case 199: + case 186: + case 71: + case 12: + case 8: + case 9: + case 13: + case 196: + case 86: + case 95: + case 99: + case 101: + case 97: + case 203: + case 204: + case 91: + return true; + default: + return false; + } } function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192: + case 193: + case 188: + case 189: + case 190: + case 191: + case 184: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { case 193: @@ -9518,21 +9753,26 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 289 - || isUnaryExpressionKind(kind); - } function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195: + case 197: + case 187: + case 194: + case 198: + case 202: + case 200: + case 289: + case 288: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 @@ -9773,6 +10013,10 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -9999,7 +10243,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); } return res; } @@ -11790,9 +12034,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288: @@ -11972,7 +12218,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -12092,9 +12338,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } function token() { return currentToken; } @@ -12217,13 +12460,11 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -12271,7 +12512,8 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var reportAtCurrentPosition = token() === 1; + return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -12504,20 +12746,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -12723,12 +12965,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26)) { continue; @@ -12753,15 +12996,15 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); if (commaStart >= 0) { result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -12803,12 +13046,12 @@ var ts; var template = createNode(196); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -12903,7 +13146,7 @@ var ts; var result = createNode(273); nextToken(); fillSignature(56, 4 | 32, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159); node.typeName = parseIdentifierName(); @@ -12961,9 +13204,10 @@ var ts; return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || isStartOfType(); + token() === 57 || + isStartOfType(true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146); if (token() === 99) { node.name = createIdentifier(true); @@ -12979,37 +13223,33 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); + node.initializer = parseInitializer(true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56)) { + return true; } - else if (flags & 4) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); - if (backwardToken) { - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { if (parseExpected(19)) { @@ -13017,7 +13257,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -13081,7 +13321,7 @@ var ts; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -13213,7 +13453,7 @@ var ts; parseExpected(94); } fillSignature(36, 4, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -13227,16 +13467,9 @@ var ts; unaryMinusExpression.operator = 38; nextToken(); } - var expression; - switch (token()) { - case 9: - case 8: - expression = parseLiteralLikeNode(token()); - break; - case 101: - case 86: - expression = parseTokenNode(); - } + var expression = token() === 101 || token() === 86 + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -13269,6 +13502,7 @@ var ts; return parseJSDocNodeWithType(274); case 51: return parseJSDocNodeWithType(271); + case 13: case 9: case 8: case 101: @@ -13300,7 +13534,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119: case 136: @@ -13325,11 +13559,14 @@ var ts; case 86: case 134: case 39: + case 55: + case 51: + case 24: return true; case 38: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -13395,13 +13632,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -13561,11 +13797,16 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58) { if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { return undefined; } + if (inParameter && requireEqualsToken) { + var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } parseExpected(58); return parseAssignmentExpressionOrHigher(); @@ -13626,8 +13867,7 @@ var ts; var parameter = createNode(146, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); @@ -13734,8 +13974,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -13764,7 +14003,8 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { + if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { return undefined; } return node; @@ -14106,7 +14346,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { @@ -14123,12 +14364,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254); @@ -15007,7 +15247,7 @@ var ts; var node = createNode(176); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { @@ -15023,7 +15263,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingPattern() { @@ -15057,7 +15297,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -15221,7 +15461,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57)) { @@ -15230,20 +15471,13 @@ var ts; var decorator = createNode(147, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } + (list || (list = [])).push(decorator); } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; + return list && createNodeArray(list, listPos); } function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -15258,17 +15492,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); + (list || (list = [])).push(modifier); } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -15278,7 +15504,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -15773,9 +15998,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267, scanner.getTokenPos()); - parseExpected(17); + if (!parseExpected(17) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576, parseType); parseExpected(18); fixupParentReferences(result); @@ -15832,6 +16059,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; if (!isJsDocStart(content, start)) { @@ -15940,7 +16169,7 @@ var ts; } function createJSDocComment() { var result = createNode(275, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -16063,21 +16292,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { var isBracketed = parseOptional(21); @@ -16167,11 +16392,11 @@ var ts; var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(true); var result = createNode(277, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -16206,19 +16431,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285, start_3); } if (child.kind === 281) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -16232,7 +16456,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -16326,7 +16552,8 @@ var ts; if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name = parseJSDocIdentifierName(); skipWhitespace(); @@ -16349,9 +16576,8 @@ var ts; var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -16443,7 +16669,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -16826,9 +17052,11 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { - symbol.declarations = []; + symbol.declarations = [node]; + } + else { + symbol.declarations.push(node); } - symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } @@ -16892,17 +17120,8 @@ var ts; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; case 283: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (ts.isIdentifier(nameIdentifier)) { - nameFromParentNode = nameIdentifier.escapedText; - } - } - } - return nameFromParentNode; + var name_2 = ts.getNameOfJSDocTypedef(node); + return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -17103,7 +17322,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; @@ -17843,9 +18062,6 @@ var ts; lastContainer = next; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { case 233: return declareModuleMember(node, symbolFlags, symbolExcludes); @@ -18007,6 +18223,9 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & 8) { + symbol.parent = container.symbol; + } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { @@ -18164,7 +18383,7 @@ var ts; inStrictMode = saveInStrictMode; } function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { + if (!ts.hasJSDocNodes(node)) { return; } for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -19341,31 +19560,38 @@ var ts; return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = ts.createMap(); - var visitedSymbols = ts.createMap(); + var visitedTypes = []; + var visitedSymbols = []; return { walkType: function (type) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitType(type); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, walkSymbol: function (symbol) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitSymbol(symbol); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, }; function visitType(type) { if (!type) { return; } - var typeIdString = type.id.toString(); - if (visitedTypes.has(typeIdString)) { + if (visitedTypes[type.id]) { return; } - visitedTypes.set(typeIdString, type); + visitedTypes[type.id] = type; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; @@ -19398,23 +19624,15 @@ var ts; visitIndexedAccessType(type); } } - function visitTypeList(types) { - if (!types) { - return; - } - for (var i = 0; i < types.length; i++) { - visitType(types[i]); - } - } function visitTypeReference(type) { visitType(type.target); - visitTypeList(type.typeArguments); + ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { visitType(getConstraintFromTypeParameter(type)); } function visitUnionOrIntersectionType(type) { - visitTypeList(type.types); + ts.forEach(type.types, visitType); } function visitIndexType(type) { visitType(type.type); @@ -19434,7 +19652,7 @@ var ts; if (signature.typePredicate) { visitType(signature.typePredicate.type); } - visitTypeList(signature.typeParameters); + ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; visitSymbol(parameter); @@ -19444,8 +19662,8 @@ var ts; } function visitInterfaceType(interfaceT) { visitObjectType(interfaceT); - visitTypeList(interfaceT.typeParameters); - visitTypeList(getBaseTypes(interfaceT)); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); visitType(interfaceT.thisType); } function visitObjectType(type) { @@ -19471,11 +19689,11 @@ var ts; if (!symbol) { return; } - var symbolIdString = ts.getSymbolId(symbol).toString(); - if (visitedSymbols.has(symbolIdString)) { + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { return; } - visitedSymbols.set(symbolIdString, symbol); + visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { return true; } @@ -19537,6 +19755,7 @@ var ts; var enumCount = 0; var symbolInstantiationDepth = 0; var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -19689,12 +19908,13 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + isArrayLikeType: isArrayLikeType, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; @@ -19773,7 +19993,8 @@ var ts; var deferredUnusedIdentifierNodes; var flowLoopStart = 0; var flowLoopCount = 0; - var visitedFlowCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); var resolutionTargets = []; @@ -19788,8 +20009,8 @@ var ts; var flowLoopNodes = []; var flowLoopKeys = []; var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; @@ -19918,6 +20139,7 @@ var ts; })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; function getJsxNamespace() { @@ -19999,7 +20221,7 @@ var ts; } function cloneSymbol(symbol) { var result = createSymbol(symbol.flags, symbol.escapedName); - result.declarations = symbol.declarations.slice(0); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -20227,10 +20449,10 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -20386,10 +20608,16 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 265); + if (lastLocation.commonJsModuleIndicator && name === "exports") { + return lastLocation.symbol; + } + } result = lookup(globals, name, meaning); } if (!result) { @@ -20501,7 +20729,7 @@ var ts; } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -20525,7 +20753,7 @@ var ts; error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -20535,14 +20763,14 @@ var ts; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -20570,11 +20798,17 @@ var ts; return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { + switch (node.kind) { + case 237: return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); + case 239: + return node.parent; + case 240: + return node.parent.parent; + case 242: + return node.parent.parent.parent; + default: + return undefined; } } function getDeclarationOfAliasSymbol(symbol) { @@ -20784,7 +21018,7 @@ var ts; var symbol; if (name.kind === 71) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, true); if (!symbol) { return undefined; } @@ -20823,7 +21057,7 @@ var ts; undefined; } else { - ts.Debug.fail("Unknown entity name kind."); + ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -20871,13 +21105,13 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -20976,10 +21210,9 @@ var ts; moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 && ts.pushIfUnique(visitedSymbols, symbol))) { return; } - visitedSymbols.push(symbol); var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports.get("__export"); if (exportStars) { @@ -21118,55 +21351,51 @@ var ts; return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { + var visitedSymbolTables = []; + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - visitedSymbolTables.push(symbols); var result = trySymbolTable(symbols); visitedSymbolTables.pop(); return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + function isUMDExportSymbol(symbol) { + return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.escapedName))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 - && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) + && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; } - }); - } - } - if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { @@ -21269,14 +21498,7 @@ var ts; isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } @@ -21298,7 +21520,7 @@ var ts; meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), @@ -21331,7 +21553,7 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(3, typeNode, sourceFile, writer); + printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; if (maxLength && result.length >= maxLength) { @@ -21613,13 +21835,13 @@ var ts; var i = 0; var qualifiedName = void 0; if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); @@ -21872,29 +22094,6 @@ var ts; } } } - function getNameOfSymbol(symbol, context) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return ts.unescapeLeadingUnderscores(symbol.escapedName); - } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { return ts.usingSingleLineStringWriter(function (writer) { @@ -21952,9 +22151,9 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol) { + function getNameOfSymbol(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -21964,6 +22163,9 @@ var ts; if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); } + if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } switch (declaration.kind) { case 199: return "(Anonymous class)"; @@ -21972,6 +22174,12 @@ var ts; return "(Anonymous function)"; } } + if (symbol.syntheticLiteralTypeOrigin) { + var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { + return "\"" + ts.escapeString(stringValue, 34) + "\""; + } + } return ts.unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder() { @@ -22168,13 +22376,13 @@ var ts; var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { - var length_3 = outerTypeParameters.length; - while (i < length_3) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { writeSymbolTypeReference(parent, typeArguments, start, i, flags); writePunctuation(writer, 23); @@ -22692,7 +22900,7 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); } else if (node.parent.kind === 246) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); @@ -22706,13 +22914,11 @@ var ts; ts.forEach(declarations, function (declaration) { getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } + ts.pushIfUnique(result, resultNode); if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -22723,8 +22929,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_4 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_4; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -23335,34 +23541,48 @@ var ts; for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } + typeParameters = ts.appendIfUnique(typeParameters, tp); } return typeParameters; } - function appendOuterTypeParameters(typeParameters, node) { + function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; if (!node) { - return typeParameters; + return undefined; } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } + switch (node.kind) { + case 229: + case 199: + case 230: + case 155: + case 156: + case 150: + case 160: + case 161: + case 273: + case 228: + case 151: + case 186: + case 187: + case 231: + case 282: + case 172: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 172) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var thisType = includeThisTypes && + (node.kind === 229 || node.kind === 199 || node.kind === 230) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); + return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; @@ -23410,7 +23630,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -23484,7 +23704,7 @@ var ts; var valueDecl = type.symbol.valueDeclaration; if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { + if (augTag && augTag.typeExpression && augTag.typeExpression.type) { baseType = getTypeFromTypeNode(augTag.typeExpression.type); } } @@ -23600,7 +23820,8 @@ var ts; var declaration = ts.find(symbol.declarations, function (d) { return d.kind === 283 || d.kind === 231; }); - var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -23934,7 +24155,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -23968,9 +24189,7 @@ var ts; if (!match) { return undefined; } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } + result = ts.appendIfUnique(result, match); } return result; } @@ -24146,7 +24365,11 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { + function addMemberForKeyType(t, propertySymbolOrIndex) { + var propertySymbol; + if (typeof propertySymbolOrIndex === "object") { + propertySymbol = propertySymbolOrIndex; + } var iterationMapper = createTypeMapper([typeParameter], [t]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); @@ -24161,6 +24384,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } + prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } else if (t.flags & 2) { @@ -24271,26 +24495,22 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getAllPossiblePropertiesOfType(type) { - if (type.flags & 65536) { - var props = ts.createSymbolTable(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var memberType = _a[_i]; - if (memberType.flags & 8190) { - continue; - } - for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { - var escapedName = _c[_b].escapedName; - if (!props.has(escapedName)) { - props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); - } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 65536)) { + return getPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var memberType = types_2[_i]; + for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); } } - return ts.arrayFrom(props.values()); - } - else { - return getPropertiesOfType(type); } + return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : @@ -24352,8 +24572,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type_2 = types_2[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type_2 = types_3[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -24416,20 +24636,15 @@ var ts; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var current = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var current = types_4[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } + props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | (!(modifiers & 24) ? 64 : 0) | (modifiers & 16 ? 128 : 0) | @@ -24555,12 +24770,7 @@ var ts; var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - if (!result) { - result = []; - } - result.push(tp); - } + result = ts.appendIfUnique(result, tp); }); return result; } @@ -24596,7 +24806,7 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512); return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { @@ -24646,11 +24856,10 @@ var ts; } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { if (!typeArguments) { typeArguments = []; @@ -24682,7 +24891,7 @@ var ts; var param = declaration.parameters[i]; var paramSymbol = param.symbol; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -24870,8 +25079,8 @@ var ts; } return anyType; } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -24884,12 +25093,20 @@ var ts; return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { @@ -24955,12 +25172,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_5 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_5) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_5 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -24977,8 +25194,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -25014,13 +25231,14 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var isJavascript = ts.isInJavaScriptFile(node); + if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -25036,7 +25254,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); } return instantiation; } @@ -25228,7 +25446,7 @@ var ts; return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); + return resolveName(undefined, name, meaning, diagnostic, name, false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -25374,6 +25592,20 @@ var ts; function containsType(types, type) { return binarySearchTypes(types, type) >= 0; } + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6368 && combined & 6368) { + return true; + } + combined |= t.flags; + if (combined & 6144 && combined & (32768 | 16777216)) { + return true; + } + } + return false; + } function addTypeToUnion(typeSet, type) { var flags = type.flags; if (flags & 65536) { @@ -25390,7 +25622,7 @@ var ts; if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192)) { + else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { if (flags & 2) typeSet.containsString = true; if (flags & 4) @@ -25408,14 +25640,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -25423,8 +25655,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -25548,8 +25780,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; addTypeToIntersection(typeSet, type); } } @@ -25695,20 +25927,6 @@ var ts; } return anyType; } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - if (accessNode) { - if (!isTypeAssignableTo(indexType, getIndexType(type))) { - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); - return unknownType; - } - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { - error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - } - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } function isGenericObjectType(type) { return type.flags & 540672 ? true : getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : @@ -25748,12 +25966,15 @@ var ts; getIntersectionType(stringIndexTypes) ]); } + if (isGenericMappedType(objectType)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; @@ -25766,7 +25987,7 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + if (indexType.flags & 65536 && !(indexType.flags & 8)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -25842,7 +26063,10 @@ var ts; return mapType(right, function (t) { return getSpreadType(left, t); }); } if (right.flags & 16777216) { - return emptyObjectType; + return nonPrimitiveType; + } + if (right.flags & (136 | 84 | 262178 | 272)) { + return left; } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); @@ -26062,10 +26286,6 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } function makeUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -26084,19 +26304,15 @@ var ts; } function createTypeMapper(sources, targets) { ts.Debug.assert(targets === undefined || sources.length === targets.length); - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; } function createTypeEraser(sources) { return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; + return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -26106,18 +26322,11 @@ var ts; createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } - function identityMapper(type) { - return type; - } function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; + return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; + return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { var result = createType(16384); @@ -26175,15 +26384,50 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } + if (symbol.isRestParameter) { + result.isRestParameter = symbol.isRestParameter; + } return result; } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (!typeParameters) { + var declaration_1 = symbol.declarations[0]; + var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + outerTypeParameters; + links.typeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + var combinedMapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function isTypeParameterReferencedWithin(tp, node) { + return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); + function checkThis(node) { + return node.kind === 169 || ts.forEachChild(node, checkThis); + } + function checkIdentifier(node) { + return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + } } function instantiateMappedType(type, mapper) { var constraintType = getConstraintTypeFromMappedType(type); @@ -26194,134 +26438,58 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); } return t; }); } } } - return instantiateMappedObjectType(type, mapper); + return instantiateAnonymousType(type, mapper); } function isMappableType(type) { return type.flags & (16384 | 32768 | 131072 | 524288); } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64, type.symbol); + if (type.objectFlags & 32) { + result.declaration = type.declaration; + } + result.target = type; + result.mapper = mapper; result.aliasSymbol = type.aliasSymbol; result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var d = typeParameters_1[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 273: - var func = node; - for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { - var p = _b[_a]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (type.objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } - return type; } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } - } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } return type; } @@ -26333,6 +26501,7 @@ var ts; switch (node.kind) { case 186: case 187: + case 151: return isContextSensitiveFunctionLikeDeclaration(node); case 178: return ts.forEach(node.properties, isContextSensitive); @@ -26346,9 +26515,6 @@ var ts; (isContextSensitive(node.left) || isContextSensitive(node.right)); case 261: return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); case 185: return isContextSensitive(node.expression); case 254: @@ -26435,7 +26601,8 @@ var ts; if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0; } - if (source.typeParameters) { + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; @@ -26678,6 +26845,13 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0; var overflow = false; var isIntersectionConstituent = false; @@ -26861,10 +27035,21 @@ var ts; } else { var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { - errorNode = prop.valueDeclaration; + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + if (ts.isIdentifier(propDeclaration.name)) { + suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } return { value: true }; @@ -27071,7 +27256,7 @@ var ts; } } else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); + var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { errorInfo = saveErrorInfo; @@ -27104,7 +27289,7 @@ var ts; } } else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); + var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { errorInfo = saveErrorInfo; @@ -27179,22 +27364,21 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + } + return 0; + } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 16777216) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 4194304)) { + if (!(targetProp.flags & 4194304)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { @@ -27466,9 +27650,10 @@ var ts; return type.flags & 16384 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } - function getTypeReferenceId(type, typeParameters) { + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } var result = "" + type.target.id; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; @@ -27480,6 +27665,9 @@ var ts; } result += "=" + index; } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } else { result += "-" + t.id; } @@ -27645,8 +27833,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -27682,7 +27870,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; + return !!(type.flags & 6368); } function isLiteralType(type) { return type.flags & 8 ? true : @@ -27710,8 +27898,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -27923,7 +28111,6 @@ var ts; function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; - context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -27961,7 +28148,7 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || + return !!(type.flags & (540672 | 262144) || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || @@ -28015,18 +28202,18 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } - function isPossiblyAssignableTo(source, target) { + function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (!(targetProp.flags & (16777216 | 4194304))) { - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (requireOptionalProperties || !(targetProp.flags & 16777216)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return false; + return targetProp; } } } - return true; + return undefined; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } @@ -28102,6 +28289,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 262144 && target.flags & 262144) { + inferFromTypes(source.type, target.type); + } + else if (source.flags & 524288 && target.flags & 524288) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (target.flags & 196608) { var targetTypes = target.types; var typeVariableCount = 0; @@ -28123,7 +28317,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 196608) { + else if (source.flags & 65536) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -28132,7 +28326,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 32768) { + if (source.flags & (32768 | 131072)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -28167,6 +28361,10 @@ var ts; return undefined; } function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } if (getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); if (constraintType.flags & 262144) { @@ -28188,7 +28386,7 @@ var ts; return; } } - if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0); inferFromSignatures(source, target, 1); @@ -28199,7 +28397,7 @@ var ts; var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -28245,8 +28443,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -28317,7 +28515,8 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -28481,8 +28680,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -28739,8 +28938,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -28809,8 +29008,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -28859,69 +29058,87 @@ var ts; } return false; } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return unknownType; + } if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } - var visitedFlowStart = visitedFlowCount; + var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; + sharedFlowCount = sharedFlowStart; var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { + if (flowDepth === 2500) { + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return unknownType; + } + flowDepth++; while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; + var flags = flow.flags; + if (flags & 1024) { + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; } } } var type = void 0; - if (flow.flags & 4096) { + if (flags & 4096) { flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flow.flags & 2048) { + else if (flags & 2048) { flow = flow.antecedent; continue; } - else if (flow.flags & 16) { + else if (flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 96) { + else if (flags & 96) { type = getTypeAtFlowCondition(flow); } - else if (flow.flags & 128) { + else if (flags & 128) { type = getTypeAtSwitchClause(flow); } - else if (flow.flags & 12) { + else if (flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flow.flags & 4 ? + type = flags & 4 ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flow.flags & 256) { + else if (flags & 256) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 2) { + else if (flags & 2) { var container = flow.container; if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { flow = container.flowNode; @@ -28932,11 +29149,12 @@ var ts; else { type = convertAutoToAny(declaredType); } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; + if (flags & 1024) { + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; } + flowDepth--; return type; } } @@ -28965,30 +29183,32 @@ var ts; return undefined; } function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 84)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + return flowType; } - return flowType; } return undefined; } @@ -29034,9 +29254,7 @@ var ts; if (type === declaredType && declaredType === initialType) { return type; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -29083,9 +29301,7 @@ var ts; if (cached_1) { return cached_1; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -29859,7 +30075,8 @@ var ts; } } } - if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var inJs = ts.isInJavaScriptFile(func); + if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { var contextualType = getApparentTypeOfContextualType(containingLiteral); @@ -29878,10 +30095,18 @@ var ts; } return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; + var parent = func.parent; + if (parent.kind === 194 && parent.operatorToken.kind === 58) { + var target = parent.left; if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); + var expression = target.expression; + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); } } } @@ -30035,7 +30260,7 @@ var ts; else if (operator === 54) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left, true); } return type; } @@ -30081,16 +30306,10 @@ var ts; } return undefined; } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIndexTypeOfContextualType(arrayContextualType, 1) + || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); } function getContextualTypeForConditionalOperand(node) { var conditional = node.parent; @@ -30164,15 +30383,20 @@ var ts; return getContextualTypeForObjectLiteralElement(parent); case 263: return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); + case 177: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } case 195: return getContextualTypeForConditionalOperand(node); case 205: ts.Debug.assert(parent.parent.kind === 196); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); + case 185: { + var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } case 256: return getContextualTypeForJsxExpression(parent); case 253: @@ -30235,8 +30459,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -30274,8 +30498,9 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elements.length; index++) { + var e = elements[index]; if (inDestructuringPattern && e.kind === 198) { var restArrayType = checkExpression(e.expression, checkMode); var restElementType = getIndexTypeOfType(restArrayType, 1) || @@ -30285,7 +30510,8 @@ var ts; } } else { - var type = checkExpressionForMutableLocation(e, checkMode); + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 198; @@ -30296,15 +30522,15 @@ var ts; type.pattern = node; return type; } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; + var contextualType_1 = getApparentTypeOfContextualType(node); + if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { + var pattern = contextualType_1.pattern; if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType_1.typeArguments[i]); } else { if (patternElement.kind !== 200) { @@ -30390,6 +30616,7 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = memberDecl.symbol; + var literalName = void 0; if (memberDecl.kind === 261 || memberDecl.kind === 262 || ts.isObjectLiteralMethod(memberDecl)) { @@ -30399,6 +30626,12 @@ var ts; } var type = void 0; if (memberDecl.kind === 261) { + if (memberDecl.name.kind === 144) { + var t = checkComputedPropertyName(memberDecl.name); + if (t.flags & 224) { + literalName = ts.escapeLeadingUnderscores("" + t.value); + } + } type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === 151) { @@ -30413,14 +30646,14 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.escapedName); + var prop = createSymbol(4 | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } @@ -30467,7 +30700,7 @@ var ts; ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); checkNodeDeferred(memberDecl); } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -30525,7 +30758,8 @@ var ts; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + return !!(type.flags & (1 | 16777216) || + getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || type.flags & 32768 && !isGenericMappedType(type) || type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } @@ -30715,8 +30949,9 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + var isJavascript = ts.isInJavaScriptFile(node); + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); @@ -30999,7 +31234,7 @@ var ts; checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = true; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -31175,19 +31410,8 @@ var ts; } return unknownType; } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - } - markPropertyAsReferenced(prop); + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -31206,6 +31430,56 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + else if (valueDeclaration.kind === 229 && + node.parent.kind !== 159 && + !ts.isInAmbientContext(valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 149: + return true; + case 261: + return false; + default: + return ts.isPartOfExpression(node) ? false : "quit"; + } + }); + } + function isPropertyDeclaredInAncestorClass(prop) { + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + ts.Debug.assert(x.length === 1); + return x[0]; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -31218,8 +31492,8 @@ var ts; } } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + if (suggestion !== undefined) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -31231,7 +31505,7 @@ var ts; return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { var symbol = getSymbol(symbols, name, meaning); if (symbol) { return symbol; @@ -31291,11 +31565,12 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) + && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -31304,15 +31579,6 @@ var ts; } } } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -31503,7 +31769,6 @@ var ts; var argCount; var typeArguments; var callIsIncomplete; - var isDecorator; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; @@ -31525,7 +31790,6 @@ var ts; } } else if (node.kind === 147) { - isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } @@ -31574,7 +31838,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } - return getSignatureInstantiation(signature, getInferredTypes(context)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -31583,13 +31847,13 @@ var ts; inference.inferredType = undefined; } } - if (ts.isExpression(node)) { + if (node.kind !== 147) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); @@ -32009,8 +32273,9 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { candidateForTypeArgumentError = originalCandidate; break; @@ -32019,7 +32284,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { candidateForArgumentError = candidate; @@ -32125,11 +32390,6 @@ var ts; if (expressionType === unknownType) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -32141,6 +32401,11 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } var callSignatures = getSignaturesOfType(expressionType, 0); @@ -32254,8 +32519,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -32280,7 +32545,7 @@ var ts; case 250: return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); @@ -32294,16 +32559,30 @@ var ts; return result; } function isJavaScriptConstructor(node) { - if (ts.isInJavaScriptFile(node)) { + if (node && ts.isInJavaScriptFile(node)) { if (ts.getJSDocClassTag(node)) return true; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; return symbol && symbol.members !== undefined; } return false; } + function getJavaScriptClassType(symbol) { + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + } + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + return getInferredClassType(symbol); + } + if (symbol.flags & 3) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + return getInferredClassType(valueType.symbol); + } + } + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -32332,13 +32611,11 @@ var ts; var funcSymbol = node.expression.kind === 71 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { - return getInferredClassType(funcSymbol); + var type = funcSymbol && getJavaScriptClassType(funcSymbol); + if (type) { + return type; } - else if (noImplicitAny) { + if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -32399,7 +32676,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); if (!resolvedRequire) { return true; } @@ -32505,7 +32782,7 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } @@ -32635,9 +32912,7 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } }); return aggregatedTypes; @@ -32681,9 +32956,7 @@ var ts; if (type.flags & 8192) { hasReturnOfTypeNever = true; } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } else { hasReturnWithNoExpression = true; @@ -32694,9 +32967,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } + ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } @@ -32949,8 +33220,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -33448,20 +33719,6 @@ var ts; var type2 = checkExpression(node.whenFalse, checkMode); return getBestChoiceType(type1, type2); } - function checkLiteralExpression(node) { - switch (node.kind) { - case 13: - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - checkGrammarNumericLiteral(node); - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); @@ -33513,9 +33770,13 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode) { + function checkExpressionForMutableLocation(node, checkMode, contextualType) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); + return shouldWiden ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, checkMode) { if (node.name.kind === 144) { @@ -33583,12 +33844,9 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); - if (typecasts && typecasts.length) { - var cast_1 = typecasts[0]; - return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); - } + var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } @@ -33604,10 +33862,14 @@ var ts; return nullWideningType; case 13: case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: + return trueType; case 86: - return checkLiteralExpression(node); + return falseType; case 196: return checkTemplateExpression(node); case 12: @@ -34156,7 +34418,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, ts.isInJavaScriptFile(typeArgumentNodes[i])); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -34224,6 +34486,10 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } return type; } if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { @@ -34489,6 +34755,7 @@ var ts; switch (d.kind) { case 230: case 231: + case 283: return 2; case 233: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 @@ -34498,6 +34765,8 @@ var ts; case 232: return 2 | 1; case 237: + case 240: + case 239: var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); @@ -34687,8 +34956,11 @@ var ts; markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } function markEntityNameOrEntityExpressionAsReference(typeName) { - var rootName = typeName && getFirstIdentifier(typeName); - var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 && symbolIsValue(rootSymbol) @@ -34794,22 +35066,12 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDoc(node) { - if (!ts.isInJavaScriptFile(node)) { - return; - } - ts.forEach(node.jsDoc, checkSourceElement); - } - function checkJSDocComment(node) { - if (node.tags) { - for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - checkSourceElement(tag); - } + function checkJSDocTypedefTag(node) { + if (!node.typeExpression) { + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } function checkFunctionOrMethodDeclaration(node) { - checkJSDoc(node); checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); @@ -34914,11 +35176,11 @@ var ts; !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); } } }); @@ -34931,15 +35193,17 @@ var ts; } return false; } - function errorUnusedLocal(node, name) { + function errorUnusedLocal(declaration, name) { + var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + var declaration_2 = ts.getRootDeclaration(node.parent); + if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 145) { return; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } function parameterNameStartsWithUnderscore(parameterName) { @@ -34955,14 +35219,14 @@ var ts; var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -34980,8 +35244,8 @@ var ts; } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -34994,7 +35258,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); } } } @@ -35005,7 +35269,14 @@ var ts; if (node.kind === 207) { checkGrammarStatementInAmbientContext(node); } - ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } if (node.locals) { registerForUnusedIdentifiersCheck(node); } @@ -35135,7 +35406,7 @@ var ts; if (symbol.flags & 1) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { @@ -35171,7 +35442,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -35232,7 +35503,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); + markPropertyAsReferenced(property, undefined); if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -36637,8 +36908,8 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } } @@ -36665,7 +36936,7 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768); } } @@ -36682,7 +36953,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); } @@ -36715,9 +36986,12 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); + if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -36747,7 +37021,7 @@ var ts; if (flags & (1920 | 64 | 384)) { return; } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); if (flags & 524288 && exportedDeclarationsCount <= 2) { return; } @@ -36762,15 +37036,24 @@ var ts; }); links.exportsChecked = true; } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } + } + function isNotAccessor(declaration) { + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var tags = _a[_i].tags; + ts.forEach(tags, checkSourceElement); + } + } var kind = node.kind; if (cancellationToken) { switch (kind) { @@ -36822,8 +37105,8 @@ var ts; case 168: case 170: return checkSourceElement(node.type); - case 275: - return checkJSDocComment(node); + case 283: + return checkJSDocTypedefTag(node); case 279: return checkSourceElement(node.typeExpression); case 273: @@ -36953,6 +37236,7 @@ var ts; ts.clear(potentialNewTargetCollisions); deferredNodes = []; deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalModule(node)) { @@ -37282,11 +37566,13 @@ var ts; return sig.thisParameter; } } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } case 169: - return getTypeFromTypeNode(node).symbol; + return getTypeFromThisTypeNode(node).symbol; + case 97: + return checkExpression(node).symbol; case 123: var constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === 152) { @@ -37300,13 +37586,17 @@ var ts; return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - return getPropertyOfType(objectType, node.text); - } - break; + var objectType = ts.isElementAccessExpression(node.parent) + ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined + : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) + ? getTypeFromTypeNode(node.parent.parent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 79: + return getSymbolOfNode(node.parent); + default: + return undefined; } - return undefined; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 262) { @@ -37417,9 +37707,9 @@ var ts; function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6) { var symbols_4 = []; - var name_2 = symbol.escapedName; + var name_3 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_2); + var symbol = getPropertyOfType(t, name_3); if (symbol) { symbols_4.push(symbol); } @@ -37520,7 +37810,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + if (resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -37663,6 +37953,14 @@ var ts; return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { @@ -37746,7 +38044,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -38022,7 +38320,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -38044,12 +38342,6 @@ var ts; case 113: case 112: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } @@ -38541,7 +38833,7 @@ var ts; currentKind = SetAccessor; } else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -38801,7 +39093,7 @@ var ts; } } } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { checkESModuleMarker(node.name); } @@ -38816,8 +39108,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; if (!ts.isOmittedExpression(element)) { return checkESModuleMarker(element.name); } @@ -38832,8 +39124,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -39282,7 +39574,7 @@ var ts; || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node) + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } ts.updateParameter = updateParameter; @@ -39898,13 +40190,26 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanTokenOrBody, bodyOrUndefined) { + var equalsGreaterThanToken; + var body; + if (bodyOrUndefined === undefined) { + equalsGreaterThanToken = node.equalsGreaterThanToken; + body = ts.cast(equalsGreaterThanTokenOrBody, ts.isConciseBody); + } + else { + equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { + return n.kind === 36; + }); + body = bodyOrUndefined; + } return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node) + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } ts.updateArrowFunction = updateArrowFunction; @@ -40009,11 +40314,23 @@ var ts; return node; } ts.createConditional = createConditional; - function updateConditional(node, condition, whenTrue, whenFalse) { + function updateConditional(node, condition) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (args.length === 2) { + var whenTrue_1 = args[0], whenFalse_1 = args[1]; + return updateConditional(node, condition, node.questionToken, whenTrue_1, node.colonToken, whenFalse_1); + } + ts.Debug.assert(args.length === 4); + var questionToken = args[0], whenTrue = args[1], colonToken = args[2], whenFalse = args[3]; return node.condition !== condition + || node.questionToken !== questionToken || node.whenTrue !== whenTrue + || node.colonToken !== colonToken || node.whenFalse !== whenFalse - ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node) + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } ts.updateConditional = updateConditional; @@ -40031,6 +40348,30 @@ var ts; : node; } ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(14); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(15); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(16); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(13); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { var node = createSynthesizedNode(197); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; @@ -41118,6 +41459,10 @@ var ts; return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction(undefined, undefined, param ? [param] : [], undefined, undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { return createBinary(left, 26, right); } @@ -41313,9 +41658,7 @@ var ts; var emitNode = getOrCreateEmitNode(node); for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { var helper = helpers_1[_i]; - if (!ts.contains(emitNode.helpers, helper)) { - emitNode.helpers = ts.append(emitNode.helpers, helper); - } + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); } } return node; @@ -41348,9 +41691,7 @@ var ts; var helper = sourceEmitHelpers[i]; if (predicate(helper)) { helpersRemoved++; - if (!ts.contains(targetEmitNode.helpers, helper)) { - targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); - } + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); } else if (helpersRemoved > 0) { sourceEmitHelpers[i - helpersRemoved] = helper; @@ -42068,11 +42409,9 @@ var ts; return recreateOuterExpressions(expression, mutableCall, 4); } } - else { - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { - return ts.setTextRange(ts.createParen(expression), expression); - } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + return ts.setTextRange(ts.createParen(expression), expression); } return expression; } @@ -42208,9 +42547,17 @@ var ts; case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } + function isIgnorableParen(node) { + return node.kind === 185 + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { if (kinds === void 0) { kinds = 7; } - if (outerExpression && isOuterExpression(outerExpression, kinds)) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; @@ -42236,7 +42583,8 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var create = hasExportStarsToExportValues && moduleKind !== ts.ModuleKind.System - && moduleKind !== ts.ModuleKind.ES2015; + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; if (!create) { var helpers = ts.getEmitHelpers(node); if (helpers) { @@ -42666,7 +43014,7 @@ var ts; case 186: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -42682,7 +43030,7 @@ var ts; case 194: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 197: @@ -43436,7 +43784,7 @@ var ts; } else { var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); exportedNames = ts.append(exportedNames, name); @@ -43729,7 +44077,7 @@ var ts; } function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -43912,6 +44260,21 @@ var ts; return saveStateAndInvoke(node, sourceElementVisitorWorker); } function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 238: + case 237: + case 243: + case 244: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + return node; + } switch (node.kind) { case 238: return visitImportDeclaration(node); @@ -43922,7 +44285,7 @@ var ts; case 244: return visitExportDeclaration(node); default: - return visitorWorker(node); + ts.Debug.fail("Unhandled ellided statement"); } } function namespaceElementVisitor(node) { @@ -44072,7 +44435,7 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && - !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { @@ -44136,8 +44499,10 @@ var ts; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -44743,7 +45108,7 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8; name.original = undefined; - name.parent = currentScope; + name.parent = ts.getParseTreeNode(currentScope); if (useFallback) { return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } @@ -44873,7 +45238,7 @@ var ts; return updated; } function visitArrowFunction(node) { - var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } function visitParameter(node) { @@ -45009,6 +45374,7 @@ var ts; return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { @@ -45468,7 +45834,6 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var currentSourceFile; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var previousOnEmitNode = context.onEmitNode; @@ -45480,10 +45845,8 @@ var ts; if (node.isDeclarationFile) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -45526,7 +45889,7 @@ var ts; : ts.visitFunctionBody(node.body, visitor, context)); } function visitArrowFunction(node) { - return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -45816,8 +46179,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { - var e = elements_4[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; if (e.kind === 263) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -45835,7 +46198,7 @@ var ts; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } else { - chunkObject.push(e); + chunkObject.push(ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } } } @@ -46025,7 +46388,7 @@ var ts; function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } @@ -46850,58 +47213,12 @@ var ts; && node.kind === 219 && !node.expression; } - function isClassLikeVariableStatement(node) { - if (!ts.isVariableStatement(node)) - return false; - var variable = ts.singleOrUndefined(node.declarationList.declarations); - return variable - && variable.initializer - && ts.isIdentifier(variable.name) - && (ts.isClassLike(variable.initializer) - || (ts.isAssignmentExpression(variable.initializer) - && ts.isIdentifier(variable.initializer.left) - && ts.isClassLike(variable.initializer.right))); - } - function isTypeScriptClassWrapper(node) { - var call = ts.tryCast(node, ts.isCallExpression); - if (!call || ts.isParseTreeNode(call) || - ts.some(call.typeArguments) || - ts.some(call.arguments)) { - return false; - } - var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); - if (!func || ts.isParseTreeNode(func) || - ts.some(func.typeParameters) || - ts.some(func.parameters) || - func.type || - !func.body) { - return false; - } - var statements = func.body.statements; - if (statements.length < 2) { - return false; - } - var firstStatement = statements[0]; - if (ts.isParseTreeNode(firstStatement) || - !ts.isClassLike(firstStatement) && - !isClassLikeVariableStatement(firstStatement)) { - return false; - } - var lastStatement = ts.elementAt(statements, -1); - var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); - if (!returnStatement || - !returnStatement.expression || - !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { - return false; - } - return true; - } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) - || isTypeScriptClassWrapper(node); + || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -48381,7 +48698,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (isTypeScriptClassWrapper(node)) { + if (ts.getEmitFlags(node) & 33554432) { return visitTypeScriptClassWrapper(node); } if (node.transformFlags & 64) { @@ -48390,7 +48707,7 @@ var ts; return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } function visitTypeScriptClassWrapper(node) { - var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); @@ -48810,7 +49127,6 @@ var ts; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; var renamedCatchVariables; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; @@ -48841,10 +49157,8 @@ var ts; if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -50588,6 +50902,7 @@ var ts; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var umdHeader = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(ts.createBlock([ ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ ts.createVariableStatement(undefined, [ @@ -50598,13 +50913,13 @@ var ts; ]), ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, [ + ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), ts.createIdentifier("factory") - ])) + ]))) ]))) ], true), undefined)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ @@ -50669,17 +50984,20 @@ var ts; } function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - if (emitAsReturn) { - var statement = ts.createReturn(currentModuleInfo.exportEquals.expression); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 | 1536); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression)); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536); - statements.push(statement); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); + statements.push(statement); + } } } } @@ -51013,7 +51331,7 @@ var ts; return statements; } if (ts.hasModifier(decl, 1)) { - var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); } if (decl.name) { @@ -51722,7 +52040,8 @@ var ts; } function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - return ts.createCall(exportFunction, undefined, [exportName, value]); + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536); + return ts.setCommentRange(ts.createCall(exportFunction, undefined, [exportName, value]), value); } function nestedElementVisitor(node) { switch (node.kind) { @@ -54853,8 +55172,13 @@ var ts; comments.reset(); setWriter(undefined); } + function emitIfPresent(node) { + if (node) { + emit(node); + } + } function emit(node) { - pipelineEmitWithNotification(3, node); + pipelineEmitWithNotification(4, node); } function emitIdentifierName(node) { pipelineEmitWithNotification(2, node); @@ -54892,7 +55216,8 @@ var ts; case 0: return pipelineEmitSourceFile(node); case 2: return pipelineEmitIdentifierName(node); case 1: return pipelineEmitExpression(node); - case 3: return pipelineEmitUnspecified(node); + case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -54903,6 +55228,11 @@ var ts; ts.Debug.assertNode(node, ts.isIdentifier); emitIdentifier(node); } + function emitMappedTypeParameter(node) { + emit(node.name); + write(" in "); + emit(node.constraint); + } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { @@ -55246,9 +55576,9 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -55260,7 +55590,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); write(";"); } @@ -55268,7 +55598,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -55277,7 +55607,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); @@ -55286,9 +55616,9 @@ var ts; function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.asteriskToken, "*"); + emitIfPresent(node.asteriskToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -55358,9 +55688,8 @@ var ts; } function emitTypeLiteral(node) { write("{"); - if (node.members.length > 0) { - emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); - } + var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; + emitList(node, node.members, flags | 262144); write("}"); } function emitArrayType(node) { @@ -55407,13 +55736,14 @@ var ts; writeLine(); increaseIndent(); } - writeIfPresent(node.readonlyToken, "readonly "); + if (node.readonlyToken) { + emit(node.readonlyToken); + write(" "); + } write("["); - emit(node.typeParameter.name); - write(" in "); - emit(node.typeParameter.constraint); + pipelineEmitWithNotification(3, node.typeParameter); write("]"); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); @@ -55453,36 +55783,25 @@ var ts; } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - var preferNewLine = node.multiLine ? 32768 : 0; - emitExpressionList(node, elements, 4466 | preferNewLine); - } + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); } function emitObjectLiteralExpression(node) { - var properties = node.properties; - if (properties.length === 0) { - write("{}"); + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); } - else { - var indentedFlag = ts.getEmitFlags(node) & 65536; - if (indentedFlag) { - increaseIndent(); - } - var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; - emitList(node, properties, 978 | allowTrailingComma | preferNewLine); - if (indentedFlag) { - decreaseIndent(); - } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; + emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); } } function emitPropertyAccessExpression(node) { @@ -55564,7 +55883,8 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); emitWithPrefix(": ", node.type); - write(" =>"); + write(" "); + emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { write("delete "); @@ -55619,12 +55939,12 @@ var ts; var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); increaseIndentIf(indentBeforeQuestion, " "); - write("?"); + emit(node.questionToken); increaseIndentIf(indentAfterQuestion, " "); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); increaseIndentIf(indentBeforeColon, " "); - write(":"); + emit(node.colonToken); increaseIndentIf(indentAfterColon, " "); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); @@ -55634,7 +55954,8 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write(node.asteriskToken ? "yield*" : "yield"); + write("yield"); + emit(node.asteriskToken); emitExpressionWithPrefix(" ", node.expression); } function emitSpreadExpression(node) { @@ -55669,27 +55990,16 @@ var ts; emit(node.literal); } function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - writeToken(17, node.pos, node); - write(" "); - writeToken(18, node.statements.end, node); - } - else { - writeToken(17, node.pos, node); - emitBlockStatements(node); - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18, node.statements.end, node); - } + writeToken(17, node.pos, node); + emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); + writeToken(18, node.statements.end, node); } - function emitBlockStatements(node) { - if (ts.getEmitFlags(node) & 1) { - emitList(node, node.statements, 384); - } - else { - emitList(node, node.statements, 65); - } + function emitBlockStatements(node, forceSingleLine) { + var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; + emitList(node, node.statements, format); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -55867,7 +56177,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.asteriskToken ? "function* " : "function "); + write("function"); + emitIfPresent(node.asteriskToken); + write(" "); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -55885,7 +56197,7 @@ var ts; if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -55895,7 +56207,7 @@ var ts; pushNameGenerationScope(); emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -56033,7 +56345,9 @@ var ts; } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - write(node.flags & 16 ? "namespace " : "module "); + if (~node.flags & 512) { + write(node.flags & 16 ? "namespace " : "module "); + } emit(node.name); var body = node.body; while (body.kind === 233) { @@ -56045,16 +56359,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isEmptyBlock(node)) { - write("{ }"); - } - else { - pushNameGenerationScope(); - write("{"); - emitBlockStatements(node); - write("}"); - popNameGenerationScope(); - } + pushNameGenerationScope(); + write("{"); + emitBlockStatements(node, isEmptyBlock(node)); + write("}"); + popNameGenerationScope(); } function emitCaseBlock(node) { writeToken(17, node.pos); @@ -56197,9 +56506,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { write("{"); - if (node.dotDotDotToken) { - write("..."); - } + emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); write("}"); } @@ -56230,13 +56537,12 @@ var ts; if (statements.length > 0) { emitTrailingCommentsOfPosition(statements.pos); } + var format = 81985; if (emitAsSingleStatement) { write(" "); - emit(statements[0]); - } - else { - emitList(parentNode, statements, 81985); + format &= ~(1 | 64); } + emitList(parentNode, statements, format); } function emitHeritageClause(node) { write(" "); @@ -56429,7 +56735,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emit(parameters[0]); + emitList(parentNode, parameters, 1360 & ~1024); } else { emitParameters(parentNode, parameters); @@ -56451,8 +56757,14 @@ var ts; if (isUndefined && format & 8192) { return; } - var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + var isEmpty = isUndefined || start >= children.length || count === 0; if (isEmpty && format & 16384) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } return; } if (format & 7680) { @@ -56465,7 +56777,7 @@ var ts; if (format & 1) { writeLine(); } - else if (format & 128) { + else if (format & 128 && !(format & 262144)) { write(" "); } } @@ -56524,7 +56836,7 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -56561,11 +56873,6 @@ var ts; write(text); } } - function writeIfPresent(node, text) { - if (node) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -56575,7 +56882,7 @@ var ts; if (onBeforeEmitToken) { onBeforeEmitToken(node); } - writeTokenText(node.kind); + write(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } @@ -56724,10 +57031,6 @@ var ts; && !ts.nodeIsSynthesized(node2) && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } - function isSingleLineEmptyBlock(block) { - return !block.multiLine - && isEmptyBlock(block); - } function isEmptyBlock(block) { return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); @@ -56971,6 +57274,8 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; @@ -56980,7 +57285,7 @@ var ts; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; @@ -57174,7 +57479,7 @@ var ts; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -57198,7 +57503,7 @@ var ts; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; + var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -57223,9 +57528,9 @@ var ts; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { - var start = diagnostic.start, length_6 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_6), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -57233,10 +57538,10 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += ts.sys.newLine; + output += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -57245,7 +57550,7 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; + output += lineContent + host.getNewLine(); output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; output += redForegroundEscapeSequence; if (i === firstLine) { @@ -57260,15 +57565,15 @@ var ts; output += lineContent.replace(/./g, "~"); } output += resetEscapeSequence; - output += ts.sys.newLine; + output += host.getNewLine(); } - output += ts.sys.newLine; + output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine; + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += host.getNewLine(); } return output; } @@ -57334,6 +57639,8 @@ var ts; ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); @@ -57383,12 +57690,11 @@ var ts; } if (!skipDefaultLib) { if (!options.lib) { - processRootFile(host.getDefaultLibFileName(options), true); + processRootFile(getDefaultLibraryFileName(), true); } else { - var libDirectory_1 = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(host.getDefaultLibFileName(options)); ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(libDirectory_1, libFileName), true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true); }); } } @@ -57421,6 +57727,7 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, @@ -57644,7 +57951,7 @@ var ts; var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -57711,6 +58018,15 @@ var ts; function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (defaultLibraryPath && defaultLibraryPath.length !== 0) { + return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + } + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } @@ -57825,9 +58141,7 @@ var ts; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - return ts.isSourceFileJavaScript(sourceFile) - ? ts.filter(diagnostics, shouldReportDiagnostic) - : diagnostics; + return ts.filter(diagnostics, shouldReportDiagnostic); }); } function shouldReportDiagnostic(diagnostic) { @@ -58043,16 +58357,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.text === b.text; - } - function getTextOfLiteral(literal) { - return literal.text; + return a.kind === 9 + ? b.kind === 9 && a.text === b.text + : b.kind === 71 && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -58168,8 +58481,8 @@ var ts; return sourceFileWithAddedExtension; } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { + function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -58235,7 +58548,7 @@ var ts; } }); if (packageId) { - var packageIdKey = packageId.name + "@" + packageId.version; + var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -58282,7 +58595,7 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -58304,7 +58617,7 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { if (previousResolution) { @@ -58317,7 +58630,7 @@ var ts; saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -58346,8 +58659,7 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); - var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); @@ -58358,13 +58670,19 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -58679,7 +58997,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -58687,6 +59005,17 @@ var ts; ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); return names; } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9) { + res.push(aug.text); + } + } + return res; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -59622,7 +59951,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; if (jsonConversionNotifier && (parentOption || knownOptions === knownRootOptions)) { @@ -59657,7 +59986,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); return null; case 9: if (!isDoubleQuotedString(valueExpression)) { @@ -59713,6 +60042,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; if (option.type === "list") { return ts.isArray(value); } @@ -59865,6 +60196,12 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } @@ -59888,7 +60225,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -59900,7 +60237,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -59909,7 +60246,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -59926,7 +60263,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -59988,7 +60325,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -60010,7 +60348,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -60164,6 +60503,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -60186,6 +60527,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -60222,7 +60565,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -60809,25 +61152,24 @@ var ts; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 || node.kind === 8) { - switch (node.parent.kind) { - case 149: - case 148: - case 261: - case 264: - case 151: - case 150: - case 153: - case 154: - case 233: - return ts.getNameOfDeclaration(node.parent) === node; - case 180: - return node.parent.argumentExpression === node; - case 144: - return true; - } + switch (node.parent.kind) { + case 149: + case 148: + case 261: + case 264: + case 151: + case 150: + case 153: + case 154: + case 233: + return ts.getNameOfDeclaration(node.parent) === node; + case 180: + return node.parent.argumentExpression === node; + case 144: + return true; + case 173: + return node.parent.parent.kind === 171; } - return false; } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; function isExpressionOfExternalModuleImportEqualsDeclaration(node) { @@ -60904,6 +61246,27 @@ var ts; return "alias"; case 283: return "type"; + case 194: + var kind = ts.getSpecialPropertyAssignmentKind(node); + var right = node.right; + switch (kind) { + case 0: + return ""; + case 1: + case 2: + var rightKind = getNodeKind(right); + return rightKind === "" ? "const" : rightKind; + case 3: + return "method"; + case 4: + return "property"; + case 5: + return ts.isFunctionExpression(right) ? "method" : "property"; + default: { + ts.assertTypeIsNever(kind); + return ""; + } + } default: return ""; } @@ -61091,7 +61454,7 @@ var ts; return undefined; } var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); + var listItemIndex = ts.indexOfNode(children, node); return { listItemIndex: listItemIndex, list: list @@ -62224,7 +62587,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_7 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -62232,8 +62595,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_7, classification: convertClassification(type) }); - lastEnd = start + length_7; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -63087,8 +63450,8 @@ var ts; continue; } var start = completePrefix.length; - var length_8 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -63348,7 +63711,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; if (sourceFile.languageVariant === 1 && location && location.parent && location.parent.kind === 252) { var tagName = location.parent.parent.openingElement.tagName; @@ -63370,14 +63733,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); + getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); } if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); @@ -63395,7 +63758,7 @@ var ts; return; } uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, true); + var displayName = getCompletionEntryDisplayName(realName, target, true, false); if (displayName) { entries.push({ name: displayName, @@ -63406,8 +63769,8 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); if (!displayName) { return undefined; } @@ -63418,13 +63781,13 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { @@ -63471,7 +63834,7 @@ var ts; var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log, true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63495,7 +63858,7 @@ var ts; var type = typeChecker.getTypeAtLocation(node.expression); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log, true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63526,7 +63889,7 @@ var ts; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } - else if (type.flags & 32) { + else if (type.flags & 32 && !(type.flags & 256)) { var name = type.value; if (!uniques.has(name)) { uniques.set(name, true); @@ -63542,8 +63905,8 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === entryName ? s : undefined; }); if (symbol) { var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { @@ -63572,7 +63935,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); - return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { @@ -63616,7 +63983,7 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -63686,6 +64053,7 @@ var ts; var semanticStart = ts.timestamp(); var isGlobalCompletion = false; var isMemberCompletion; + var allowStringLiteral = false; var isNewIdentifierLocation; var keywordFilters = 0; var symbols = []; @@ -63718,7 +64086,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 277: @@ -63983,6 +64351,7 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; + allowStringLiteral = true; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { @@ -63990,7 +64359,7 @@ var ts; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); existingMembers = objectLikeContainer.properties; } else { @@ -64419,7 +64788,7 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { var name = symbol.name; if (!name) return undefined; @@ -64429,11 +64798,11 @@ var ts; return undefined; } } - return getCompletionEntryDisplayName(name, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return undefined; + return allowStringLiteral ? JSON.stringify(name) : undefined; } return name; } @@ -64537,6 +64906,14 @@ var ts; return node.parent; } } + function getPropertiesForCompletion(type, checker) { + if (!(type.flags & 65536)) { + return checker.getPropertiesOfType(type); + } + var types = type.types; + var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 || checker.isArrayLikeType(memberType)); }); + return checker.getAllPossiblePropertiesOfTypes(filteredTypes); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -65085,11 +65462,10 @@ var ts; var bucket = getBucketForCompilationSettings(key, true); var entry = bucket.get(path); if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); entry = { sourceFile: sourceFile, - languageServiceRefCount: 0, + languageServiceRefCount: 1, owners: [] }; bucket.set(path, entry); @@ -65098,9 +65474,9 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); } - } - if (acquiring) { - entry.languageServiceRefCount++; + if (acquiring) { + entry.languageServiceRefCount++; + } } return entry.sourceFile; } @@ -65265,7 +65641,6 @@ var ts; } } function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { @@ -65296,10 +65671,10 @@ var ts; searchForNamedImport(decl.exportClause); return; } - if (!decl.importClause) { + var importClause = decl.importClause; + if (!importClause) { return; } - var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { handleNamespaceImportLike(namedBindings.name); @@ -65315,39 +65690,42 @@ var ts; addSearch(name, defaultImportAlias); } if (!isForRename && exportKind === 1) { - ts.Debug.assert(exportName === "default"); searchForNamedImport(namedBindings); } } } function handleNamespaceImportLike(importName) { - if (exportKind === 2 && (!isForRename || importName.escapedText === exportName)) { + if (exportKind === 2 && (!isForRename || isNameMatch(importName.escapedText))) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) { - for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).escapedText !== exportName) { - continue; - } - if (propertyName) { - singleReferences.push(propertyName); - if (!isForRename) { - addSearch(name, checker.getSymbolAtLocation(name)); - } - } - else { - var localSymbol = element.kind === 246 && element.propertyName - ? checker.getExportSpecifierLocalTargetSymbol(element) - : checker.getSymbolAtLocation(name); - addSearch(name, localSymbol); + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + singleReferences.push(propertyName); + if (!isForRename) { + addSearch(name, checker.getSymbolAtLocation(name)); } } + else { + var localSymbol = element.kind === 246 && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } } } + function isNameMatch(name) { + return name === exportSymbol.escapedName || exportKind !== 0 && name === "default"; + } } function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); @@ -65508,7 +65886,8 @@ var ts; function getExportAssignmentExport(ex) { var exportingModuleSymbol = ex.symbol.parent; ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + var exportKind = ex.isExportEquals ? 2 : 1; + return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -65537,7 +65916,8 @@ var ts; if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } - if (symbolName(importedSymbol) === symbol.escapedName) { + var importedName = symbolName(importedSymbol); + if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { return __assign({ kind: 0, symbol: importedSymbol }, isImport); } } @@ -65713,8 +66093,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_2 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -65722,8 +66102,8 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword", displayParts: [{ text: name_4, kind: "keyword" }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword", displayParts: [{ text: name_5, kind: "keyword" }] }; } case "this": { var node_5 = def.node; @@ -65764,8 +66144,10 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 79 + || ts.isAnyDeclarationName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -65807,7 +66189,7 @@ var ts; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; - var writeAccess = isWriteAccess(node); + var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node), kind: writeAccess ? "writtenReference" : "reference", @@ -65825,20 +66207,8 @@ var ts; } return ts.createTextSpanFromBounds(start, end); } - function isWriteAccess(node) { - if (ts.isAnyDeclarationName(node)) { - return true; - } - var parent = node.parent; - switch (parent && parent.kind) { - case 193: - case 192: - return true; - case 194: - return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); - default: - return false; - } + function isWriteAccessForReference(node) { + return node.kind === 79 || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -66163,7 +66533,7 @@ var ts; return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { - switch (node && node.kind) { + switch (node.kind) { case 71: return node.text.length === searchSymbolName.length; case 9: @@ -66171,6 +66541,8 @@ var ts; node.text.length === searchSymbolName.length; case 8: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 79: + return "default".length === searchSymbolName.length; default: return false; } @@ -66683,17 +67055,21 @@ var ts; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); + addRootSymbols(bindingElementPropertySymbol); } - for (var _i = 0, _a = checker.getRootSymbols(symbol); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); + addRootSymbols(symbol); + return result; + function addRootSymbols(sym) { + for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { + var rootSymbol = _a[_i]; + if (rootSymbol !== sym) { + result.push(rootSymbol); + } + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); + } } } - return result; } function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { if (!symbol) { @@ -66746,23 +67122,28 @@ var ts; } } var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); - if (bindingElementPropertySymbol && search.includes(bindingElementPropertySymbol)) { - return bindingElementPropertySymbol; - } - return ts.forEach(state.checker.getRootSymbols(referenceSymbol), function (rootSymbol) { - if (search.includes(rootSymbol)) { - return rootSymbol; - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { - return undefined; + if (bindingElementPropertySymbol) { + var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); + if (fromBindingElement) + return fromBindingElement; + } + return findRootSymbol(referenceSymbol); + function findRootSymbol(sym) { + return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + if (search.includes(rootSymbol)) { + return rootSymbol; + } + if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + return undefined; + } + var result = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); + return ts.find(result, search.includes); } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); - return ts.find(result, search.includes); - } - return undefined; - }); + return undefined; + }); + } } function getNameFromObjectLiteralElement(node) { if (node.name.kind === 144) { @@ -67279,43 +67660,31 @@ var ts; if (!tokenAtPos || tokenStart < position) { return undefined; } - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 228: - case 151: - case 152: - case 229: - case 208: - break findOwner; - case 265: - return undefined; - case 233: - if (commentOwner.parent.kind === 233) { - return undefined; - } - break findOwner; - } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; } - if (!commentOwner || commentOwner.getStart() < position) { + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart() < position) { return undefined; } - var parameters = getParametersForJsDocOwningNode(commentOwner); var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; + if (parameters) { + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } } var preamble = "/**" + newLine + @@ -67327,18 +67696,38 @@ var ts; return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 208) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + function getCommentOwnerInfo(tokenAtPos) { + for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 228: + case 151: + case 152: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 229: + return { commentOwner: commentOwner }; + case 208: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 265: + return undefined; + case 233: + return commentOwner.parent.kind === 233 ? undefined : { commentOwner: commentOwner }; + case 194: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0) { + return undefined; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } } } - return ts.emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 185) { @@ -67536,148 +67925,149 @@ var ts; return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { - if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { - return; - } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - if (patternMatcher.patternContainsDots) { - var containers = getContainers(declaration); - if (!containers) { - return true; - } - matches = patternMatcher.getMatches(containers, name); - if (!matches) { - return; - } - } - var fileName = sourceFile.fileName; - var matchKind = bestMatchKind(matches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); - } - } + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } - rawItems = ts.filter(rawItems, function (item) { - var decl = item.declaration; - if (decl.kind === 239 || decl.kind === 242 || decl.kind === 237) { - var importer = checker.getSymbolAtLocation(decl.name); - var imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName; - } - else { - return true; - } - }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); } - var items = ts.map(rawItems, createNavigateToItem); - return items; - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - if (!match.isCaseSensitive) { - return false; + return rawItems.map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); + if (!matches) { + return; + } + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (!shouldKeepItem(declaration, checker)) { + continue; + } + var containerMatches = matches; + if (patternMatcher.patternContainsDots) { + containerMatches = patternMatcher.getMatches(getContainers(declaration), name); + if (!containerMatches) { + continue; } } - return true; + var matchKind = bestMatchKind(containerMatches); + var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); + rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); } - function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 144) { - return tryAddComputedPropertyName(name.expression, containers, true); - } - else { - return false; - } - } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 239: + case 242: + case 237: + var importer = checker.getSymbolAtLocation(declaration.name); + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function allMatchesAreCaseSensitive(matches) { + ts.Debug.assert(matches.length > 0); + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; + if (!match.isCaseSensitive) { + return false; } - return true; } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (text !== undefined) { - if (includeLastPortion) { + return true; + } + function tryAddSingleDeclarationName(declaration, containers) { + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = ts.getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { containers.unshift(text); } - return true; - } - if (expression.kind === 179) { - var propertyAccess = expression; - if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; } - return tryAddComputedPropertyName(propertyAccess.expression, containers, true); } - return false; } - function getContainers(declaration) { - var containers = []; - var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144) { - if (!tryAddComputedPropertyName(name.expression, containers, false)) { - return undefined; - } + return true; + } + function tryAddComputedPropertyName(expression, containers, includeLastPortion) { + var text = ts.getTextOfIdentifierOrLiteral(expression); + if (text !== undefined) { + if (includeLastPortion) { + containers.unshift(text); } - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; - } - declaration = ts.getContainerNode(declaration); + return true; + } + if (expression.kind === 179) { + var propertyAccess = expression; + if (includeLastPortion) { + containers.unshift(propertyAccess.name.text); } - return containers; + return tryAddComputedPropertyName(propertyAccess.expression, containers, true); } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } + return false; + } + function getContainers(declaration) { + var containers = []; + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { + return undefined; } - return bestMatchKind; } - function compareNavigateToItems(i1, i2) { - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + declaration = ts.getContainerNode(declaration); + while (declaration) { + if (!tryAddSingleDeclarationName(declaration, containers)) { + return undefined; + } + declaration = ts.getContainerNode(declaration); } - function createNavigateToItem(rawItem) { - var declaration = rawItem.declaration; - var container = ts.getContainerNode(declaration); - var containerName = container && ts.getNameOfDeclaration(container); - return { - name: rawItem.name, - kind: ts.getNodeKind(declaration), - kindModifiers: ts.getNodeModifiers(declaration), - matchKind: ts.PatternMatchKind[rawItem.matchKind], - isCaseSensitive: rawItem.isCaseSensitive, - fileName: rawItem.fileName, - textSpan: ts.createTextSpanFromNode(declaration), - containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" - }; + return containers; + } + function bestMatchKind(matches) { + ts.Debug.assert(matches.length > 0); + var bestMatchKind = ts.PatternMatchKind.camelCase; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; + var kind = match.kind; + if (kind < bestMatchKind) { + bestMatchKind = kind; + } } + return bestMatchKind; + } + function compareNavigateToItems(i1, i2) { + return i1.matchKind - i2.matchKind || + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" + }; } - NavigateTo.getNavigateToItems = getNavigateToItems; })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); var ts; @@ -67825,16 +68215,22 @@ var ts; break; case 176: case 226: - var decl = node; - var name = decl.name; + var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); } - else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { - addChildrenRecursively(decl.initializer); + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + addChildrenRecursively(initializer); + } + else { + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } } else { - addNodeWithRecursiveChild(decl, decl.initializer); + addNodeWithRecursiveChild(node, initializer); } break; case 187: @@ -67844,8 +68240,8 @@ var ts; break; case 232: startNode(node); - for (var _d = 0, _e = node.members; _d < _e.length; _d++) { - var member = _e[_d]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -67856,8 +68252,8 @@ var ts; case 199: case 230: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -67874,13 +68270,15 @@ var ts; addLeafNode(node); break; default: - ts.forEach(node.jsDoc, function (jsDoc) { - ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283) { - addLeafNode(tag); - } + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 283) { + addLeafNode(tag); + } + }); }); - }); + } ts.forEachChild(node, addChildrenRecursively); } } @@ -68193,7 +68591,14 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 186 || node.kind === 187 || node.kind === 199; + switch (node.kind) { + case 187: + case 186: + case 199: + return true; + default: + return false; + } } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); @@ -68203,11 +68608,15 @@ var ts; (function (OutliningElementsCollector) { var collapseText = "..."; var maxDepth = 20; + var defaultLabel = "#region"; + var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { var elements = []; var depth = 0; + var regions = []; walk(sourceFile); - return elements; + gatherRegions(); + return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { @@ -68272,6 +68681,36 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187; } + function gatherRegions() { + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); + var comment = sourceFile.text.substring(currentLineStart, lineEnd); + var result = comment.match(regionMatch); + if (result && !ts.isInComment(sourceFile, currentLineStart)) { + if (!result[1]) { + var start = sourceFile.getFullText().indexOf("//", currentLineStart); + var textSpan = ts.createTextSpanFromBounds(start, lineEnd); + var region = { + textSpan: textSpan, + hintSpan: textSpan, + bannerText: result[2] || defaultLabel, + autoCollapse: false + }; + regions.push(region); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + elements.push(region); + } + } + } + } + } function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -68988,11 +69427,9 @@ var ts; return true; } token = nextToken(); - var i = 0; while (token !== 22 && token !== 1) { if (token === 9) { recordModuleName(); - i++; } token = nextToken(); } @@ -69132,10 +69569,16 @@ var ts; return ts.createTextSpan(start, width); } function nodeIsEligibleForRename(node) { - return node.kind === 71 || - node.kind === 9 || - ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - ts.isThis(node); + switch (node.kind) { + case 71: + case 9: + case 99: + return true; + case 8: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); @@ -69374,7 +69817,7 @@ var ts; if (isTypeParameterList) { isVariadic = false; prefixDisplayParts.push(ts.punctuationPart(27)); - var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { @@ -69509,7 +69952,7 @@ var ts; if (rootSymbolFlags & (98308 | 3)) { return "property"; } - ts.Debug.assert(!!(rootSymbolFlags & 8192)); + ts.Debug.assert(!!(rootSymbolFlags & (8192 | 16))); }); if (!unionPropertyKind) { var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); @@ -70035,7 +70478,6 @@ var ts; (function (formatting) { var standardScanner = ts.createScanner(5, false, 0); var jsxScanner = ts.createScanner(5, false, 1); - var scanner; var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -70045,9 +70487,8 @@ var ts; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); - function getFormattingScanner(text, languageVariant, startPos, endPos) { - ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); - scanner = languageVariant === 1 ? jsxScanner : standardScanner; + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 ? jsxScanner : standardScanner; scanner.setText(text); scanner.setTextPos(startPos); var wasNewLine = true; @@ -70056,38 +70497,28 @@ var ts; var savedPos; var lastScanAction; var lastTokenInfo; - return { + var res = cb({ advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, - close: function () { - ts.Debug.assert(scanner !== undefined); - lastTokenInfo = undefined; - scanner.setText(undefined); - scanner = undefined; - } - }; + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; function advance() { - ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - if (trailingTrivia) { - ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4; - } - else { - wasNewLine = false; - } + wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4; } - leadingTrivia = undefined; - trailingTrivia = undefined; - if (!isStarted) { + else { scanner.scan(); } + leadingTrivia = undefined; + trailingTrivia = undefined; var pos = scanner.getStartPos(); while (pos < endPos) { var t = scanner.getToken(); @@ -70101,23 +70532,18 @@ var ts; kind: t }; pos = scanner.getStartPos(); - if (!leadingTrivia) { - leadingTrivia = []; - } - leadingTrivia.push(item); + leadingTrivia = ts.append(leadingTrivia, item); } savedPos = scanner.getStartPos(); } function shouldRescanGreaterThanToken(node) { - if (node) { - switch (node.kind) { - case 31: - case 66: - case 67: - case 47: - case 46: - return true; - } + switch (node.kind) { + case 31: + case 66: + case 67: + case 47: + case 46: + return true; } return false; } @@ -70128,13 +70554,13 @@ var ts; case 251: case 252: case 250: - return node.kind === 71; + return ts.isKeyword(node.kind) || node.kind === 71; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 10; + return node.kind === 10; } function shouldRescanSlashToken(container) { return container.kind === 12; @@ -70147,14 +70573,7 @@ var ts; return t === 41 || t === 63; } function readTokenInfo(n) { - ts.Debug.assert(scanner !== undefined); - if (!isOnToken()) { - return { - leadingTrivia: leadingTrivia, - trailingTrivia: undefined, - token: undefined - }; - } + ts.Debug.assert(isOnToken()); var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 : shouldRescanSlashToken(n) @@ -70174,32 +70593,7 @@ var ts; scanner.setTextPos(savedPos); scanner.scan(); } - var currentToken = scanner.getToken(); - if (expectedScanAction === 1 && currentToken === 29) { - currentToken = scanner.reScanGreaterToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 1; - } - else if (expectedScanAction === 2 && startsWithSlashToken(currentToken)) { - currentToken = scanner.reScanSlashToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 2; - } - else if (expectedScanAction === 3 && currentToken === 18) { - currentToken = scanner.reScanTemplateToken(); - lastScanAction = 3; - } - else if (expectedScanAction === 4 && currentToken === 71) { - currentToken = scanner.scanJsxIdentifier(); - lastScanAction = 4; - } - else if (expectedScanAction === 5) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5; - } - else { - lastScanAction = 0; - } + var currentToken = getNextToken(n, expectedScanAction); var token = { pos: scanner.getStartPos(), end: scanner.getTextPos(), @@ -70230,8 +70624,46 @@ var ts; lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0; + switch (expectedScanAction) { + case 1: + if (token === 29) { + lastScanAction = 1; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2: + if (startsWithSlashToken(token)) { + lastScanAction = 2; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3: + if (token === 18) { + lastScanAction = 3; + return scanner.reScanTemplateToken(); + } + break; + case 4: + lastScanAction = 4; + return scanner.scanJsxIdentifier(); + case 5: + lastScanAction = 5; + return scanner.reScanJsxToken(); + case 0: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } function isOnToken() { - ts.Debug.assert(scanner !== undefined); var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); return startPos < endPos && current !== 1 && !ts.isTrivia(current); @@ -70360,11 +70792,6 @@ var ts; this.Operation = Operation; this.Flag = Flag; } - Rule.prototype.toString = function () { - return "[desc=" + this.Descriptor + "," + - "operation=" + this.Operation + "," + - "flag=" + this.Flag + "]"; - }; return Rule; }()); formatting.Rule = Rule; @@ -70683,16 +71110,16 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - } - Rules.prototype.getRuleName = function (rule) { - var o = this; - for (var name in o) { - if (o[name] === rule) { - return name; + if (ts.Debug.isDebugging) { + var o = this; + for (var name in o) { + var rule = o[name]; + if (rule instanceof formatting.Rule) { + rule.debugName = name; + } } } - throw new Error("Unknown rule"); - }; + } Rules.IsOptionEnabled = function (optionName) { return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; }; @@ -70831,8 +71258,7 @@ var ts; return true; case 207: { var blockParent = context.currentTokenParent.parent; - if (blockParent.kind !== 187 && - blockParent.kind !== 186) { + if (!blockParent || blockParent.kind !== 187 && blockParent.kind !== 186) { return true; } } @@ -71242,15 +71668,9 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); this.rulesMap = formatting.RulesMap.create(activeRules); } - RulesProvider.prototype.getRuleName = function (rule) { - return this.globalRules.getRuleName(rule); - }; - RulesProvider.prototype.getRuleByName = function (name) { - return this.globalRules[name]; - }; RulesProvider.prototype.getRulesMap = function () { return this.rulesMap; }; @@ -71443,7 +71863,7 @@ var ts; } function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { @@ -71458,7 +71878,7 @@ var ts; } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); @@ -71484,7 +71904,6 @@ var ts; trimTrailingWhitespacesForRemainingRange(); } } - formattingScanner.close(); return edits; function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || @@ -71681,6 +72100,7 @@ var ts; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; @@ -72474,6 +72894,8 @@ var ts; case 241: case 246: case 242: + case 261: + case 149: return true; } return false; @@ -72518,15 +72940,21 @@ var ts; var textChanges; (function (textChanges) { function getPos(n) { - return n["__pos"]; + var result = n["__pos"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); n["__pos"] = pos; } function getEnd(n) { - return n["__end"]; + var result = n["__end"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); n["__end"] = end; } var Position; @@ -72573,7 +73001,8 @@ var ts; if (startLine === fullStartLine) { return position === Position.Start ? start : fullStart; } - var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + 1, sourceFile); + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } @@ -72599,9 +73028,6 @@ var ts; } return s; } - function getNewlineKind(context) { - return context.newLineCharacter === "\n" ? 1 : 0; - } var ChangeTracker = (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -72610,8 +73036,8 @@ var ts; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } - ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -72637,7 +73063,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(node); + var index = ts.indexOfNode(containingList, node); if (index < 0) { return this; } @@ -72752,7 +73178,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(after); + var index = ts.indexOfNode(containingList, after); if (index < 0) { return this; } @@ -72915,10 +73341,9 @@ var ts; var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); - printer.writeNode(3, node, sourceFile, writer); + printer.writeNode(4, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - textChanges.getNonformattedText = getNonformattedText; function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { @@ -72929,7 +73354,6 @@ var ts; var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } - textChanges.applyFormatting = applyFormatting; function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -72943,13 +73367,10 @@ var ts; } function assignPositionsToNode(node) { var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); - var newNode = ts.nodeIsSynthesized(visited) - ? visited - : (Proxy.prototype = visited, new Proxy()); + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); newNode.end = getEnd(node); return newNode; - function Proxy() { } } function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); @@ -73082,7 +73503,15 @@ var ts; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); if (actions && actions.length > 0) { - allActions = allActions.concat(actions); + for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { + var action = actions_1[_i]; + if (action === undefined) { + context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); + } + else { + allActions.push(action); + } + } } }); return allActions; @@ -73111,6 +73540,10 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextLength(context) { + return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + } + ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); var ts; (function (ts) { @@ -73129,7 +73562,7 @@ var ts; var leftText = qualifiedName.left.getText(sourceFile); var rightText = qualifiedName.right.getText(sourceFile); var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); return [{ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), @@ -73258,7 +73691,7 @@ var ts; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), @@ -73273,7 +73706,7 @@ var ts; return actions; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), @@ -73299,7 +73732,7 @@ var ts; } typeNode = typeNode || ts.createKeywordTypeNode(119); var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); (actions || (actions = [])).push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), @@ -73309,7 +73742,7 @@ var ts; var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), @@ -73322,7 +73755,7 @@ var ts; if (token.parent.parent.kind === 181) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? @@ -73453,7 +73886,7 @@ var ts; } } } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); changeTracker.deleteNode(sourceFile, superCall); return [{ @@ -73485,7 +73918,7 @@ var ts; if (token.kind !== 123) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var superCall = ts.createStatement(ts.createCall(ts.createSuper(), undefined, ts.emptyArray)); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); return [{ @@ -73518,7 +73951,7 @@ var ts; if (!(extendsToken && extendsToken.kind === 85)) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108)); for (var i = 1; i < heritageClauses.length; i++) { var keywordToken = heritageClauses[i].getFirstToken(); @@ -73547,7 +73980,7 @@ var ts; if (token.kind !== 71) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), @@ -73563,8 +73996,8 @@ var ts; (function (codefix) { codefix.registerCodeFix({ errorCodes: [ - ts.Diagnostics._0_is_declared_but_never_used.code, - ts.Diagnostics.Property_0_is_declared_but_never_used.code + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code ], getCodeActions: function (context) { var sourceFile = context.sourceFile; @@ -73700,19 +74133,19 @@ var ts; } } function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); } function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteRange(sourceFile, range)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); } function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeInList(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); } function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeRange(sourceFile, start, end)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); } function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { return { @@ -73735,11 +74168,30 @@ var ts; function getActionsForJSDocTypes(context) { var sourceFile = context.sourceFile; var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var decl = ts.findAncestor(node, function (n) { return n.kind === 226; }); + var decl = ts.findAncestor(node, function (n) { + return n.kind === 202 || + n.kind === 155 || + n.kind === 156 || + n.kind === 228 || + n.kind === 153 || + n.kind === 157 || + n.kind === 172 || + n.kind === 151 || + n.kind === 150 || + n.kind === 146 || + n.kind === 149 || + n.kind === 148 || + n.kind === 154 || + n.kind === 231 || + n.kind === 184 || + n.kind === 226; + }); if (!decl) return; var checker = context.program.getTypeChecker(); var jsdocType = decl.type; + if (!jsdocType) + return; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; @@ -73918,28 +74370,21 @@ var ts; if (cached) { return cached; } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); - } - } + var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); cachedImportDeclarations[moduleSymbolId] = existingDeclarations; return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; - } - if (node.kind === 237) { - return node; - } - node = node.parent; + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238: + return parent; + case 248: + return parent.parent; + default: + return undefined; } - return undefined; } } function getUniqueSymbolId(symbol) { @@ -74281,7 +74726,7 @@ var ts; } } function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + return ts.textChanges.ChangeTracker.fromContext(context); } function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { return { @@ -74361,7 +74806,7 @@ var ts; (function (codefix) { function newNodesToChanges(newNodes, insertAfter, context) { var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { var newNode = newNodes_1[_i]; changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); @@ -74587,7 +75032,7 @@ var ts; return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { @@ -74616,7 +75061,9 @@ var ts; deleteCallback(); } return { - edits: changeTracker.getChanges() + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined, }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } @@ -74754,7 +75201,7 @@ var ts; }; refactor.registerRefactor(extractMethod); function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -74767,11 +75214,11 @@ var ts; var usedNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var extr = extractions_1[_i]; - if (extr.errors && extr.errors.length) { + var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; + if (errors.length) { continue; } - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); if (!usedNames.has(description)) { usedNames.set(description, true); actions.push({ @@ -74792,16 +75239,13 @@ var ts; }]; } function getEditsForAction(context, actionName) { - var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); var index = +parsedIndexMatch[1]; ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - var extractions = getPossibleExtractions(targetRange, context, index); - ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); - return ({ edits: extractions[0].changes }); + return getExtractionAtIndex(targetRange, context, index); } var Messages; (function (Messages) { @@ -74830,9 +75274,12 @@ var ts; RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; - })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + })(RangeFacts || (RangeFacts = {})); function getRangeToExtract(sourceFile, span) { - var length = span.length || 0; + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + } var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); var declarations = []; @@ -74875,18 +75322,13 @@ var ts; if (errors) { return { errors: errors }; } - var range = ts.isStatement(start) - ? [start] - : start.parent && start.parent.kind === 210 - ? [start.parent] - : start; - return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; } function createErrorResult(sourceFile, start, length, message) { return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; } function checkRootNode(node) { - if (ts.isIdentifier(node)) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } return undefined; @@ -74923,7 +75365,7 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; } if (ts.isInAmbientContext(nodeToCheck)) { @@ -74979,39 +75421,26 @@ var ts; return false; } var savedPermittedJumps = permittedJumps; - if (node.parent) { - switch (node.parent.kind) { - case 211: - if (node.parent.thenStatement === node || node.parent.elseStatement === node) { - permittedJumps = 0; - } - break; - case 224: - if (node.parent.tryBlock === node) { - permittedJumps = 0; - } - else if (node.parent.finallyBlock === node) { - permittedJumps = 4; - } - break; - case 260: - if (node.parent.block === node) { - permittedJumps = 0; - } - break; - case 257: - if (node.expression !== node) { - permittedJumps |= 1; - } - break; - default: - if (ts.isIterationStatement(node.parent, false)) { - if (node.parent.statement === node) { - permittedJumps |= 1 | 2; - } - } - break; - } + switch (node.kind) { + case 211: + permittedJumps = 0; + break; + case 224: + permittedJumps = 0; + break; + case 207: + if (node.parent && node.parent.kind === 224 && node.finallyBlock === node) { + permittedJumps = 4; + } + break; + case 257: + permittedJumps |= 1; + break; + default: + if (ts.isIterationStatement(node, false)) { + permittedJumps |= 1 | 2; + } + break; } switch (node.kind) { case 169: @@ -75036,7 +75465,7 @@ var ts; } } else { - if (!(permittedJumps & (218 ? 1 : 2))) { + if (!(permittedJumps & (node.kind === 218 ? 1 : 2))) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } @@ -75065,6 +75494,15 @@ var ts; } } extractMethod_1.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isPartOfExpression(node)) { + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } function isValidExtractionTarget(node) { return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } @@ -75091,9 +75529,21 @@ var ts; } return scopes; } - extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; - function getPossibleExtractions(targetRange, context, requestedChangesIndex) { - if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; + ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + } + extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + return scopes.map(function (scope, i) { + return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + }); + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; if (targetRange === undefined) { return undefined; @@ -75103,86 +75553,62 @@ var ts; return undefined; } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; - context.cancellationToken.throwIfCancellationRequested(); - if (requestedChangesIndex !== undefined) { - if (errorsPerScope[requestedChangesIndex].length) { - return undefined; - } - return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; - } - else { - return scopes.map(function (scope, i) { - var errors = errorsPerScope[i]; - if (errors.length) { - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - errors: errors - }; - } - return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; - }); - } + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getDescriptionForScope(scope) { - if (ts.isFunctionLike(scope)) { - switch (scope.kind) { - case 152: - return "constructor"; - case 186: - return scope.name - ? "function expression " + scope.name.getText() - : "anonymous function expression"; - case 228: - return "function " + scope.name.getText(); - case 187: - return "arrow function"; - case 151: - return "method " + scope.name.getText(); - case 153: - return "get " + scope.name.getText(); - case 154: - return "set " + scope.name.getText(); - } - } - else if (ts.isModuleBlock(scope)) { - return "namespace " + scope.parent.name.getText(); - } - else if (ts.isClassLike(scope)) { - return scope.kind === 229 - ? "class " + scope.name.text - : scope.name.text - ? "class expression " + scope.name.text - : "anonymous class expression"; - } - else if (ts.isSourceFile(scope)) { - return "file '" + scope.fileName + "'"; - } - else { - return "unknown"; + return ts.isFunctionLikeDeclaration(scope) + ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? "method in " + getDescriptionForClassLikeDeclaration(scope) + : "function in " + getDescriptionForModuleLikeDeclaration(scope); + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 152: + return "constructor"; + case 186: + return scope.name + ? "function expression '" + scope.name.text + "'" + : "anonymous function expression"; + case 228: + return "function '" + scope.name.text + "'"; + case 187: + return "arrow function"; + case 151: + return "method '" + scope.name.getText(); + case 153: + return "'get " + scope.name.getText() + "'"; + case 154: + return "'set " + scope.name.getText() + "'"; + default: + ts.Debug.assertNever(scope); } } - function getUniqueName(isNameOkay) { + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 229 + ? "class '" + scope.name.text + "'" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 234 + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? "module scope" : "global scope"; + } + function getUniqueName(fileText) { var functionNameText = "newFunction"; - if (isNameOkay(functionNameText)) { - return functionNameText; - } - var i = 1; - while (!isNameOkay(functionNameText = "newFunction_" + i)) { - i++; + for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { + functionNameText = "newFunction_" + i; } return functionNameText; } function extractFunctionInScope(node, scope, _a, range, context) { - var usagesInScope = _a.usages, substitutions = _a.substitutions; + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); - var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var functionNameText = getUniqueName(file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var functionReference = ts.createIdentifier(functionNameText); var returnType = undefined; var parameters = []; var callArguments = []; @@ -75201,11 +75627,19 @@ var ts; } callArguments.push(ts.createIdentifier(name)); }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, undefined); }) + : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); returnType = checker.typeToTypeNode(contextualType); } - var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; var newFunction; if (ts.isClassLike(scope)) { var modifiers = isJS ? [] : [ts.createToken(112)]; @@ -75215,15 +75649,23 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.createToken(120)); } - newFunction = ts.createMethod(undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, [], parameters, returnType, body); + newFunction = ts.createMethod(undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, typeParameters, parameters, returnType, body); + } + else { + newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); } else { - newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, [], parameters, returnType, body); + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var newNodes = []; - var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, undefined, callArguments); + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, callArguments); if (range.facts & RangeFacts.IsGenerator) { call = ts.createYield(ts.createToken(39), call); } @@ -75244,6 +75686,9 @@ var ts; } else { newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } } } else { @@ -75273,63 +75718,152 @@ var ts; else { changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); } - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - changes: changeTracker.getChanges() - }; - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); - } - function generateReturnValueProperty() { - return "__return"; - } - function transformFunctionBody(body) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; - } - var returnValueProperty; - var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - if (writes || substitutions.size) { - var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (assignments.length === 1) { - rewrittenStatements.push(ts.createReturn(assignments[0].name)); - } - else { - rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); - } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getRenameLocation(edits, renameFilename, functionNameText) { + var delta = 0; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { + var change = textChanges_2[_b]; + var span_17 = change.span, newText = change.newText; + var index = newText.indexOf(functionNameText); + if (index !== -1) { + return span_17.start + delta + index; + } + delta += newText.length - span_17.length; + } + } + throw new Error(); + } + function getFirstDeclaration(type) { + var firstDeclaration = undefined; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + if (declaration1) { + if (declaration2) { + var positionDiff = declaration1.pos - declaration2.pos; + if (positionDiff !== 0) { + return positionDiff; } - return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; } else { - return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; - } - function visitor(node) { - if (node.kind === 219 && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = generateReturnValueProperty(); - } - assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); - } - if (assignments.length === 1) { - return ts.createReturn(assignments[0].name); - } - else { - return ts.createReturn(ts.createObjectLiteral(assignments)); + return 1; + } + } + else if (declaration2) { + return -1; + } + var name1 = type1.symbol ? type1.symbol.getName() : ""; + var name2 = type2.symbol ? type2.symbol.getName() : ""; + var nameDiff = ts.compareStrings(name1, name2); + if (nameDiff !== 0) { + return nameDiff; + } + return type1.id - type2.id; + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, writes, substitutions, hasReturn) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !hasReturn && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 219 && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); } else { - var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return ts.createReturn(ts.createObjectLiteral(assignments)); } } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } } } - extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLike(scope)) { + var body = scope.body; + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertTypeIsNever(scope); + } + return ts.emptyArray; + } + function getNodeToInsertBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + }); + } + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } function isReadonlyArray(v) { return ts.isArray(v); } @@ -75343,21 +75877,50 @@ var ts; Usage[Usage["Read"] = 1] = "Read"; Usage[Usage["Write"] = 2] = "Write"; })(Usage || (Usage = {})); - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); var usagesPerScope = []; var substitutionsPerScope = []; var errorsPerScope = []; var visibleDeclarationsInExtractedRange = []; for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { var _ = scopes_1[_i]; - usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); errorsPerScope.push([]); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { + for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + ts.Debug.assert(i_1 === scopes.length); + } var _loop_8 = function (i) { var hasWrite = false; var readonlyClassPropertyWrite = undefined; @@ -75375,7 +75938,7 @@ var ts; errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); } }; for (var i = 0; i < scopes.length; i++) { @@ -75385,8 +75948,35 @@ var ts; ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function hasTypeParameters(node) { + return ts.isDeclarationWithTypeParameters(node) && + node.typeParameters !== undefined && + node.typeParameters.length > 0; + } + function isInGenericContext(node) { + for (; node; node = node.parent) { + if (hasTypeParameters(node)) { + return true; + } + } + return false; + } + function recordTypeParameterUsages(type) { + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.flags & 16384) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } if (ts.isDeclaration(node) && node.symbol) { visibleDeclarationsInExtractedRange.push(node.symbol); } @@ -75428,7 +76018,9 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = checker.getSymbolAtLocation(identifier); + var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); if (!symbol) { return undefined; } @@ -75452,7 +76044,7 @@ var ts; if (!declInFile) { return undefined; } - if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { return undefined; } if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { @@ -75473,7 +76065,9 @@ var ts; substitutionsPerScope[i].set(symbolId, substitution); } else if (isTypeName) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + if (!(symbol.flags & 262144)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } } else { usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); @@ -76059,6 +76653,10 @@ var ts; } } break; + case 194: + if (ts.getSpecialPropertyAssignmentKind(node) !== 0) { + addDeclaration(node); + } default: ts.forEachChild(node, visit); } @@ -76366,7 +76964,7 @@ var ts; oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || oldSettings.baseUrl !== newSettings.baseUrl || !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); var compilerHost = { @@ -76495,17 +77093,17 @@ var ts; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); - return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { - return semanticDiagnostics; + return semanticDiagnostics.slice(); } var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); - return ts.concatenate(semanticDiagnostics, declarationDiagnostics); + return semanticDiagnostics.concat(declarationDiagnostics); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); @@ -76534,7 +77132,7 @@ var ts; return undefined; } var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { case 71: @@ -76567,6 +77165,20 @@ var ts; tags: displayPartsDocumentationsAndKind.tags }; } + function getSymbolAtLocationForQuickInfo(node, checker) { + if ((ts.isIdentifier(node) || ts.isStringLiteral(node)) + && ts.isPropertyAssignment(node.parent) + && node.parent.name === node) { + var type = checker.getContextualType(node.parent.parent); + if (type) { + var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; + } + } + } + return checker.getSymbolAtLocation(node); + } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); @@ -76624,7 +77236,19 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + var sourceFiles = []; + if (options && options.isForRename) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + sourceFiles.push(sourceFile); + } + } + } + else { + sourceFiles = program.getSourceFiles().slice(); + } + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); @@ -76929,7 +77553,7 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: host.getNewLine(), + newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), rulesProvider: getRuleProvider(formatOptions), cancellationToken: cancellationToken }; @@ -77008,7 +77632,7 @@ var ts; nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } ts.forEachChild(node, walk); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; ts.forEachChild(jsDoc, walk); @@ -78278,16 +78902,18 @@ var ts; }()); server.TextStorage = TextStorage; var ScriptInfo = (function () { - function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, isDynamic) { if (hasMixedContent === void 0) { hasMixedContent = false; } + if (isDynamic === void 0) { isDynamic = false; } this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; this.hasMixedContent = hasMixedContent; + this.isDynamic = isDynamic; this.containingProjects = []; this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); this.textStorage = new TextStorage(host, fileName); - if (hasMixedContent) { + if (hasMixedContent || isDynamic) { this.textStorage.reload(""); } this.scriptKind = scriptKind @@ -78304,7 +78930,7 @@ var ts; }; ScriptInfo.prototype.close = function () { this.isOpen = false; - this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.textStorage.useText(this.hasMixedContent || this.isDynamic ? "" : undefined); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.getSnapshot = function () { @@ -78413,7 +79039,7 @@ var ts; this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { - if (this.hasMixedContent) { + if (this.hasMixedContent || this.isDynamic) { this.reload(""); } else { @@ -78749,7 +79375,7 @@ var ts; var server; (function (server) { function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent; + return !scriptInfo.hasMixedContent && !scriptInfo.isDynamic; } server.shouldEmitFile = shouldEmitFile; var BuilderFileInfo = (function () { @@ -78877,7 +79503,7 @@ var ts; }; NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; if (info.updateShapeSignature()) { var options = this.project.getCompilerOptions(); if (options && (options.out || options.outFile)) { @@ -78974,7 +79600,7 @@ var ts; }; ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; var fileInfo = this.getFileInfo(scriptInfo.path); if (!fileInfo || !fileInfo.updateShapeSignature()) { return singleFileResult; @@ -79437,24 +80063,23 @@ var ts; var file = changedFiles_1[_i]; this.cachedUnresolvedImportsPerFile.remove(file); } - var unresolvedImports; - if (hasChanges || changedFiles.length) { - var result = []; - for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { - var sourceFile = _b[_a]; - this.extractUnresolvedImportsFromSourceFile(sourceFile, result); - } - this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); - } - unresolvedImports = this.lastCachedUnresolvedImportsList; - var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); - if (this.setTypings(cachedTypings)) { - hasChanges = this.updateGraphWorker() || hasChanges; - } if (this.languageServiceEnabled) { + if (hasChanges || changedFiles.length) { + var result = []; + for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { + var sourceFile = _b[_a]; + this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + } + this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); + } + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } this.builder.onProjectUpdateGraph(); } else { + this.lastCachedUnresolvedImportsList = undefined; this.builder.clear(); } if (hasChanges) { @@ -79597,7 +80222,8 @@ var ts; return { info: info, projectErrors: this.getGlobalProjectErrors() }; } var lastReportedFileNames_1 = this.lastReportedFileNames; - var currentFiles_1 = ts.arrayToSet(this.getFileNames()); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); var added_1 = []; var removed_1 = []; var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; @@ -79617,7 +80243,8 @@ var ts; } else { var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToSet(projectFileNames); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + this.lastReportedFileNames = ts.arrayToSet(projectFileNames.concat(externalFiles)); this.lastReportedVersion = this.projectStructureVersion; return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; } @@ -79785,8 +80412,11 @@ var ts; } if (this.projectService.globalPlugins) { var _loop_10 = function (globalPluginName) { + if (!globalPluginName) + return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; + this_2.projectService.logger.info("Loading global plugin " + globalPluginName); this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; var this_2 = this; @@ -79798,6 +80428,7 @@ var ts; }; ConfiguredProject.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); var log = function (message) { _this.projectService.logger.info(message); }; @@ -79809,7 +80440,7 @@ var ts; return; } } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name + " anywhere in paths: " + searchPaths.join(",")); + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); }; ConfiguredProject.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { @@ -79825,7 +80456,16 @@ var ts; serverHost: this.projectService.host }; var pluginModule = pluginModuleFactory({ typescript: ts }); - this.languageService = pluginModule.create(info); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; this.plugins.push(pluginModule); } catch (e) { @@ -79854,6 +80494,9 @@ var ts; } catch (e) { _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } } })); }; @@ -80089,11 +80732,13 @@ var ts; getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, + isDynamicFile: function (x) { return x[0] === "^"; }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, - hasMixedContent: function (x) { return x.hasMixedContent; } + hasMixedContent: function (x) { return x.hasMixedContent; }, + isDynamicFile: function (x) { return x.fileName[0] === "^"; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { @@ -80747,7 +81392,8 @@ var ts; var _this = this; var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); + var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); + this.addFilesToProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); if (!sizeLimitExceeded) { this.watchConfigDirectoryForProject(project, projectOptions); @@ -80768,15 +81414,16 @@ var ts; var errors; for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { var f = files_4[_i]; - var rootFilename = propertyReader.getFileName(f); + var rootFileName = propertyReader.getFileName(f); var scriptKind = propertyReader.getScriptKind(f); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - if (this.host.fileExists(rootFilename)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName === rootFilename, undefined, scriptKind, hasMixedContent); + var isDynamicFile = propertyReader.isDynamicFile(f); + if (isDynamicFile || this.host.fileExists(rootFileName)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFileName), clientFileName === rootFileName, undefined, scriptKind, hasMixedContent, isDynamicFile); project.addRoot(info); } else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFileName)); } } project.setProjectErrors(ts.concatenate(configFileErrors, errors)); @@ -80804,7 +81451,8 @@ var ts; for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { var f = newUncheckedFiles_1[_i]; var newRootFile = propertyReader.getFileName(f); - if (!this.host.fileExists(newRootFile)) { + var isDynamic = propertyReader.isDynamicFile(f); + if (!isDynamic && !this.host.fileExists(newRootFile)) { (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); continue; } @@ -80815,7 +81463,7 @@ var ts; if (!scriptInfo) { var scriptKind = propertyReader.getScriptKind(f); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent, isDynamic); } } newRootScriptInfos.push(scriptInfo); @@ -80954,16 +81602,16 @@ var ts; }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; - if (!info.hasMixedContent) { + if (!info.hasMixedContent && !info.isDynamic) { var fileName_2 = info.fileName; info.setWatcher(this.host.watchFile(fileName_2, function (_) { return _this.onSourceFileChanged(fileName_2); })); } }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, isDynamic) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - if (openedByClient || this.host.fileExists(fileName)) { - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); + if (openedByClient || isDynamic || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, isDynamic); this.filenameToScriptInfo.set(info.path, info); if (openedByClient) { if (fileContent === undefined) { @@ -81112,7 +81760,7 @@ var ts; for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } @@ -81150,7 +81798,9 @@ var ts; var configuredProject = this.findConfiguredProjectByProjectName(configFile); if (configuredProject && configuredProject.deleteOpenRef() === 0) { this.removeProject(configuredProject); + return true; } + return false; }; ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { if (suppressRefresh === void 0) { suppressRefresh = false; } @@ -81447,8 +82097,8 @@ var ts; { start: start, end: end, text: text, code: code, category: category, source: source }; } function allEditsBeforePos(edits, pos) { - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var edit = edits_1[_i]; + for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) { + var edit = edits_2[_i]; if (ts.textSpanEnd(edit.span) >= pos) { return false; } @@ -81929,7 +82579,7 @@ var ts; }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = []; + var diags = server.emptyArray; if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { diags = project.getLanguageService().getSemanticDiagnostics(file); } @@ -82617,12 +83267,12 @@ var ts; return undefined; } if (simplifiedResult) { - var span_17 = helpItems.applicableSpan; + var span_18 = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_17.start), - end: scriptInfo.positionToLineOffset(span_17.start + span_17.length) + start: scriptInfo.positionToLineOffset(span_18.start), + end: scriptInfo.positionToLineOffset(span_18.start + span_18.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -82824,7 +83474,7 @@ var ts; var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, args.formatOptions ? server.convertFormatOptions(args.formatOptions) : this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); if (result === undefined) { return { edits: [] @@ -82928,6 +83578,9 @@ var ts; return; } var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + if (fileNamesInProject.length === 0) { + return; + } var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; @@ -82942,7 +83595,7 @@ var ts; else { var info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isScriptOpen()) { - if (fileNameInProject.indexOf(".d.ts") > 0) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) { veryLowPriorityFiles.push(fileNameInProject); } else { @@ -82954,11 +83607,9 @@ var ts; } } } - fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); - if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, delay, false); - } + var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); + var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + this.updateErrorCheck(next, checkList, delay, false); }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); @@ -83927,13 +84578,16 @@ var ts; var _this = this; this.telemetryEnabled = telemetryEnabled; this.logger = logger; + this.host = host; this.globalTypingsCacheLocation = globalTypingsCacheLocation; this.typingSafeListLocation = typingSafeListLocation; this.typesMapLocation = typesMapLocation; this.npmLocation = npmLocation; this.newLine = newLine; this.installerPidReported = false; - this.throttledOperations = new server.ThrottledOperations(host); + this.activeRequestCount = 0; + this.requestQueue = []; + this.requestMap = ts.createMap(); if (eventPort) { var s_1 = net.connect({ port: eventPort }, function () { _this.socket = s_1; @@ -84008,70 +84662,124 @@ var ts; this.logger.info("Scheduling throttled operation: " + JSON.stringify(request)); } } - this.throttledOperations.schedule(project.getProjectName(), 250, function () { + var operationId = project.getProjectName(); + var operation = function () { if (_this.logger.hasLevel(server.LogLevel.verbose)) { _this.logger.info("Sending request: " + JSON.stringify(request)); } _this.installer.send(request); - }); + }; + var queuedRequest = { operationId: operationId, operation: operation }; + if (this.activeRequestCount < NodeTypingsInstaller.maxActiveRequestCount) { + this.scheduleRequest(queuedRequest); + } + else { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Deferring request for: " + operationId); + } + this.requestQueue.push(queuedRequest); + this.requestMap.set(operationId, queuedRequest); + } }; NodeTypingsInstaller.prototype.handleMessage = function (response) { if (this.logger.hasLevel(server.LogLevel.verbose)) { this.logger.info("Received response: " + JSON.stringify(response)); } - if (response.kind === server.EventInitializationFailed) { - if (!this.eventSender) { - return; - } - var body = { - message: response.message - }; - var eventName = "typesInstallerInitializationFailed"; - this.eventSender.event(body, eventName); - return; - } - if (response.kind === server.EventBeginInstallTypes) { - if (!this.eventSender) { - return; - } - var body = { - eventId: response.eventId, - packages: response.packagesToInstall, - }; - var eventName = "beginInstallTypes"; - this.eventSender.event(body, eventName); - return; - } - if (response.kind === server.EventEndInstallTypes) { - if (!this.eventSender) { - return; - } - if (this.telemetryEnabled) { - var body_1 = { - telemetryEventName: "typingsInstalled", - payload: { - installedPackages: response.packagesToInstall.join(","), - installSuccess: response.installSuccess, - typingsInstallerVersion: response.typingsInstallerVersion + switch (response.kind) { + case server.EventInitializationFailed: + { + if (!this.eventSender) { + break; } - }; - var eventName_1 = "telemetry"; - this.eventSender.event(body_1, eventName_1); - } - var body = { - eventId: response.eventId, - packages: response.packagesToInstall, - success: response.installSuccess, - }; - var eventName = "endInstallTypes"; - this.eventSender.event(body, eventName); - return; + var body = { + message: response.message + }; + var eventName = "typesInstallerInitializationFailed"; + this.eventSender.event(body, eventName); + break; + } + case server.EventBeginInstallTypes: + { + if (!this.eventSender) { + break; + } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + var eventName = "beginInstallTypes"; + this.eventSender.event(body, eventName); + break; + } + case server.EventEndInstallTypes: + { + if (!this.eventSender) { + break; + } + if (this.telemetryEnabled) { + var body_1 = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion + } + }; + var eventName_1 = "telemetry"; + this.eventSender.event(body_1, eventName_1); + } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + var eventName = "endInstallTypes"; + this.eventSender.event(body, eventName); + break; + } + case server.ActionInvalidate: + { + this.projectService.updateTypingsForProject(response); + break; + } + case server.ActionSet: + { + if (this.activeRequestCount > 0) { + this.activeRequestCount--; + } + else { + ts.Debug.fail("Received too many responses"); + } + while (this.requestQueue.length > 0) { + var queuedRequest = this.requestQueue.shift(); + if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { + this.requestMap.delete(queuedRequest.operationId); + this.scheduleRequest(queuedRequest); + break; + } + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Skipping defunct request for: " + queuedRequest.operationId); + } + } + this.projectService.updateTypingsForProject(response); + if (this.socket) { + this.sendEvent(0, "setTypings", response); + } + break; + } + default: + ts.assertTypeIsNever(response); } - this.projectService.updateTypingsForProject(response); - if (response.kind === server.ActionSet && this.socket) { - this.sendEvent(0, "setTypings", response); + }; + NodeTypingsInstaller.prototype.scheduleRequest = function (request) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Scheduling request for: " + request.operationId); } + this.activeRequestCount++; + this.host.setTimeout(request.operation, NodeTypingsInstaller.requestDelayMillis); }; + NodeTypingsInstaller.maxActiveRequestCount = 10; + NodeTypingsInstaller.requestDelayMillis = 100; return NodeTypingsInstaller; }()); var IOSession = (function (_super) { @@ -84176,7 +84884,6 @@ var ts; if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; var nextFileToCheck = 0; - var watchTimer; return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile }; function getModifiedTime(fileName) { return fs.statSync(fileName).mtime; @@ -84206,7 +84913,7 @@ var ts; }); } function startWatchTimer() { - watchTimer = setInterval(function () { + setInterval(function () { var count = 0; var nextToCheck = nextFileToCheck; var firstCheck = -1; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 513d8079a40fb..01827a24d0ae4 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -435,6 +435,9 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -447,7 +450,7 @@ declare namespace ts { type EqualsToken = Token; type AsteriskToken = Token; type EqualsGreaterThanToken = Token; - type EndOfFileToken = Token; + type EndOfFileToken = Token & JSDocContainer; type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; @@ -485,6 +488,7 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; + parent?: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { @@ -495,16 +499,18 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends NamedDeclaration { + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type?: TypeNode; + type: TypeNode | undefined; } - interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.CallSignature; } - interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; @@ -520,7 +526,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends NamedDeclaration { + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -537,14 +543,14 @@ declare namespace ts { name: BindingName; initializer?: Expression; } - interface PropertySignature extends TypeElement { + interface PropertySignature extends TypeElement, JSDocContainer { kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } - interface PropertyDeclaration extends ClassElement { + interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; questionToken?: QuestionToken; name: PropertyName; @@ -556,27 +562,30 @@ declare namespace ts { name?: PropertyName; } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; - interface PropertyAssignment extends ObjectLiteralElement { + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.PropertyAssignment; name: PropertyName; questionToken?: QuestionToken; initializer: Expression; } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } - interface SpreadAssignment extends ObjectLiteralElement { + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.SpreadAssignment; expression: Expression; } interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name?: DeclarationName; + name: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -596,7 +605,7 @@ declare namespace ts { } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; type ArrayBindingElement = BindingElement | OmittedExpression; - interface FunctionLikeDeclarationBase extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; @@ -609,16 +618,16 @@ declare namespace ts { name?: Identifier; body?: FunctionBody; } - interface MethodSignature extends SignatureDeclaration, TypeElement { + interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -627,20 +636,20 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; } @@ -654,10 +663,10 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclaration { + interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { + interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.ConstructorType; } type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; @@ -668,6 +677,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; + parent?: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -712,7 +722,6 @@ declare namespace ts { } interface MappedTypeNode extends TypeNode, Declaration { kind: SyntaxKind.MappedType; - parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; typeParameter: TypeParameterDeclaration; questionToken?: QuestionToken; @@ -720,7 +729,7 @@ declare namespace ts { } interface LiteralTypeNode extends TypeNode { kind: SyntaxKind.LiteralType; - literal: Expression; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; } interface StringLiteral extends LiteralExpression { kind: SyntaxKind.StringLiteral; @@ -854,12 +863,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -905,7 +914,7 @@ declare namespace ts { expression: Expression; literal: TemplateMiddle | TemplateTail; } - interface ParenthesizedExpression extends PrimaryExpression { + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } @@ -915,6 +924,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; + parent?: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { @@ -1072,11 +1082,11 @@ declare namespace ts { kind: SyntaxKind.Block; statements: NodeArray; } - interface VariableStatement extends Statement { + interface VariableStatement extends Statement, JSDocContainer { kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } - interface ExpressionStatement extends Statement { + interface ExpressionStatement extends Statement, JSDocContainer { kind: SyntaxKind.ExpressionStatement; expression: Expression; } @@ -1157,7 +1167,7 @@ declare namespace ts { statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { + interface LabeledStatement extends Statement, JSDocContainer { kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; @@ -1179,19 +1189,21 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; - interface ClassLikeDeclaration extends NamedDeclaration { + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.ClassDeclaration; name?: Identifier; } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { kind: SyntaxKind.ClassExpression; } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; @@ -1201,7 +1213,7 @@ declare namespace ts { name?: PropertyName; questionToken?: QuestionToken; } - interface InterfaceDeclaration extends DeclarationStatement { + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; @@ -1214,26 +1226,26 @@ declare namespace ts { token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } - interface TypeAliasDeclaration extends DeclarationStatement { + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends NamedDeclaration { + interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; initializer?: Expression; } - interface EnumDeclaration extends DeclarationStatement { + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleName = Identifier | StringLiteral; type ModuleBody = NamespaceBody | JSDocNamespaceBody; - interface ModuleDeclaration extends DeclarationStatement { + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; parent?: ModuleBody | SourceFile; name: ModuleName; @@ -1255,7 +1267,7 @@ declare namespace ts { statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; - interface ImportEqualsDeclaration extends DeclarationStatement { + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; parent?: SourceFile | ModuleBlock; name: Identifier; @@ -1365,7 +1377,7 @@ declare namespace ts { kind: SyntaxKind.JSDocOptionalType; type: TypeNode; } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { kind: SyntaxKind.JSDocFunctionType; } interface JSDocVariadicType extends JSDocType { @@ -1375,6 +1387,7 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; + parent?: HasJSDoc; tags: NodeArray | undefined; comment: string | undefined; } @@ -1429,7 +1442,6 @@ declare namespace ts { interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: ReadonlyArray; - jsDocTypeTag?: JSDocTypeTag; isArrayType?: boolean; } const enum FlowFlags { @@ -1503,10 +1515,10 @@ declare namespace ts { endOfFileToken: Token; fileName: string; text: string; - amdDependencies: AmdDependency[]; + amdDependencies: ReadonlyArray; moduleName: string; - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; hasNoDefaultLib: boolean; @@ -1514,7 +1526,7 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; - sourceFiles: SourceFile[]; + sourceFiles: ReadonlyArray; } interface JsonSourceFile extends SourceFile { jsonObject?: ObjectLiteralExpression; @@ -1533,7 +1545,7 @@ declare namespace ts { readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; } class OperationCanceledException { } @@ -1542,15 +1554,16 @@ declare namespace ts { throwIfCancellationRequested(): void; } interface Program extends ScriptReferenceHost { - getRootFileNames(): string[]; - getSourceFiles(): SourceFile[]; + getRootFileNames(): ReadonlyArray; + getSourceFiles(): ReadonlyArray; emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; } interface CustomTransformers { before?: TransformerFactory[]; @@ -1583,7 +1596,7 @@ declare namespace ts { } interface EmitResult { emitSkipped: boolean; - diagnostics: Diagnostic[]; + diagnostics: ReadonlyArray; emittedFiles: string[]; } interface TypeChecker { @@ -1857,6 +1870,7 @@ declare namespace ts { IndexedAccess = 524288, NonPrimitive = 16777216, Literal = 224, + Unit = 6368, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, @@ -2032,7 +2046,7 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[]; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2199,6 +2213,7 @@ declare namespace ts { } interface PackageId { name: string; + subModuleName: string; version: string; } const enum Extension { @@ -2214,14 +2229,15 @@ declare namespace ts { interface ResolvedTypeReferenceDirective { primary: boolean; resolvedFileName?: string; + packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; failedLookupLocations: string[]; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2283,7 +2299,8 @@ declare namespace ts { SourceFile = 0, Expression = 1, IdentifierName = 2, - Unspecified = 3, + MappedTypeParameter = 3, + Unspecified = 4, } interface TransformationContext { getCompilerOptions(): CompilerOptions; @@ -2343,6 +2360,9 @@ declare namespace ts { const versionMajorMinor = "2.6"; const version: string; } +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; +} declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { @@ -2433,7 +2453,18 @@ declare namespace ts { function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; function unescapeLeadingUnderscores(identifier: __String): string; function unescapeIdentifier(id: string): string; - function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined; + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + function getJSDocType(node: Node): TypeNode | undefined; + function getJSDocReturnType(node: Node): TypeNode | undefined; + function getJSDocTags(node: Node): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -2805,8 +2836,8 @@ declare namespace ts { function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; @@ -2835,6 +2866,7 @@ declare namespace ts { function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -2852,8 +2884,13 @@ declare namespace ts { function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; @@ -2992,10 +3029,12 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: SourceFile[]): Bundle; - function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createBundle(sourceFiles: ReadonlyArray): Bundle; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[]): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3062,10 +3101,10 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; getNewLine(): string; } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { interface Node { @@ -3121,7 +3160,7 @@ declare namespace ts { interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; - getLineStarts(): number[]; + getLineStarts(): ReadonlyArray; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; } @@ -3273,15 +3312,15 @@ declare namespace ts { inlineable?: boolean; actions: RefactorActionInfo[]; } - type RefactorActionInfo = { + interface RefactorActionInfo { name: string; description: string; - }; - type RefactorEditInfo = { + } + interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename?: string; - renameLocation?: number; - }; + renameFilename: string | undefined; + renameLocation: number | undefined; + } interface TextInsertion { newText: string; caretOffset: number; @@ -4041,10 +4080,10 @@ declare namespace ts.server.protocol { inlineable?: boolean; actions: RefactorActionInfo[]; } - type RefactorActionInfo = { + interface RefactorActionInfo { name: string; description: string; - }; + } interface GetEditsForRefactorRequest extends Request { command: CommandTypes.GetEditsForRefactor; arguments: GetEditsForRefactorRequestArgs; @@ -4052,15 +4091,16 @@ declare namespace ts.server.protocol { type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { refactor: string; action: string; + formatOptions?: FormatCodeSettings; }; interface GetEditsForRefactorResponse extends Response { body?: RefactorEditInfo; } - type RefactorEditInfo = { + interface RefactorEditInfo { edits: FileCodeEdits[]; renameLocation?: Location; renameFilename?: string; - }; + } interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; @@ -4943,13 +4983,14 @@ declare namespace ts.server { readonly fileName: NormalizedPath; readonly scriptKind: ScriptKind; hasMixedContent: boolean; + isDynamic: boolean; readonly containingProjects: Project[]; private formatCodeSettings; readonly path: Path; private fileWatcher; private textStorage; private isOpen; - constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent?: boolean); + constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent?: boolean, isDynamic?: boolean); isScriptOpen(): boolean; open(newText: string): void; close(): void; @@ -5295,7 +5336,7 @@ declare namespace ts.server { interface SafeList { [name: string]: { match: RegExp; - exclude?: Array>; + exclude?: (string | number)[][]; types?: string[]; }; } @@ -5412,7 +5453,7 @@ declare namespace ts.server { getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; watchClosedScriptInfo(info: ScriptInfo): void; - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, isDynamic?: boolean): ScriptInfo; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfoForPath(fileName: Path): ScriptInfo; setHostConfiguration(args: protocol.ConfigureRequestArguments): void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 263796daa7acd..cbc35cf18766d 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -705,6 +705,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; @@ -1065,6 +1066,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1097,7 +1099,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; @@ -1164,6 +1167,12 @@ var ts; ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; @@ -1795,6 +1804,26 @@ var ts; return to; } ts.addRange = addRange; + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; function stableSort(array, comparer) { if (comparer === void 0) { comparer = compareValues; } return array @@ -1941,6 +1970,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2105,6 +2144,8 @@ var ts; ts.cast = cast; function noop() { } ts.noop = noop; + function identity(x) { return x; } + ts.identity = identity; function notImplemented() { throw new Error("Not implemented"); } @@ -2181,12 +2222,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2428,12 +2468,8 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2470,7 +2506,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3096,6 +3132,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3233,6 +3273,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); var ts; (function (ts) { @@ -3797,8 +3843,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4118,7 +4164,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4191,6 +4239,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4308,7 +4357,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4413,17 +4462,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -4514,6 +4562,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4561,7 +4610,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); var ts; @@ -4583,7 +4632,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -4607,15 +4655,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -4649,7 +4696,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -4771,7 +4818,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } if (node.kind === 286 && node._children.length > 0) { @@ -4808,6 +4855,15 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; + } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -4835,6 +4891,7 @@ var ts; case 16: return "}" + escapeText(node.text, 96) + "`"; case 8: + case 12: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -4932,6 +4989,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155: + case 156: + case 150: + case 157: + case 160: + case 161: + case 273: + case 229: + case 199: + case 230: + case 231: + case 282: + case 228: + case 151: + case 152: + case 153: + case 154: + case 186: + case 187: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -5579,59 +5664,62 @@ var ts; case 8: case 9: case 99: - var parent_3 = node.parent; - switch (parent_3.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: - return parent_3.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: - return parent_3.expression === node; - case 214: - var forStatement = parent_3; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215: - case 216: - var forInStatement = parent_3; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || - forInStatement.expression === node; - case 184: - case 202: - return node === parent_3.expression; - case 205: - return node === parent_3.expression; - case 144: - return node === parent_3.expression; - case 147: - case 256: - case 255: - case 263: - return true; - case 201: - return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); - default: - if (isPartOfExpression(parent_3)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -5795,14 +5883,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -5810,14 +5890,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -5849,22 +5921,17 @@ var ts; getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_5 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_5; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getParameterSymbolFromJSDoc(node) { if (node.symbol) { return node.symbol; @@ -5890,38 +5957,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -5933,7 +5968,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -6334,9 +6369,9 @@ var ts; || kind === 265; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -6600,13 +6635,17 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" }); + var escapedNullRegExp = /\\0[0-9]/g; function escapeString(s, quoteChar) { var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -6886,7 +6925,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -6895,7 +6934,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -6904,7 +6943,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -7293,10 +7332,10 @@ var ts; } function getEnumMembers(enumObject) { var result = []; - for (var name_6 in enumObject) { - var value = enumObject[name_6]; + for (var name_5 in enumObject) { + var value = enumObject[name_5]; if (typeof value === "number") { - result.push([value, name_6]); + result.push([value, name_5]); } } return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); @@ -7463,6 +7502,41 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + AccessKind[AccessKind["Read"] = 0] = "Read"; + AccessKind[AccessKind["Write"] = 1] = "Write"; + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0; + switch (parent.kind) { + case 193: + case 192: + var operator = parent.operator; + return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; + case 194: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; + case 179: + return parent.name !== node ? 0 : accessKind(parent); + default: + return 0; + } + function writeOrReadWrite() { + return parent.parent && parent.parent.kind === 210 ? 1 : 2; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -7741,6 +7815,56 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 208: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210: + var expr = hostNode.expression; + switch (expr.kind) { + case 179: + return expr.name; + case 180: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1: + return undefined; + case 185: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -7760,11 +7884,78 @@ var ts; return undefined; } } + else if (declaration.kind === 283) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_6 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_6; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getJSDocTypeTag(node) { + var tag = getFirstJSDocTag(node, 281); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -8397,8 +8588,7 @@ var ts; } ts.isToken = isToken; function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; function isLiteralKind(kind) { @@ -8483,16 +8673,27 @@ var ts; return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152: - case 186: case 228: - case 187: case 151: - case 150: + case 152: case 153: case 154: + case 186: + case 187: + return true; + default: + return false; + } + } + function isFunctionLikeKind(kind) { + switch (kind) { + case 150: case 155: case 156: case 157: @@ -8500,10 +8701,15 @@ var ts; case 273: case 161: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; return kind === 152 @@ -8657,52 +8863,61 @@ var ts; || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 91 - || kind === 203 - || kind === 204; - } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179: + case 180: + case 182: + case 181: + case 249: + case 250: + case 183: + case 177: + case 185: + case 178: + case 199: + case 186: + case 71: + case 12: + case 8: + case 9: + case 13: + case 196: + case 86: + case 95: + case 99: + case 101: + case 97: + case 203: + case 204: + case 91: + return true; + default: + return false; + } } function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192: + case 193: + case 188: + case 189: + case 190: + case 191: + case 184: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { case 193: @@ -8715,21 +8930,26 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 289 - || isUnaryExpressionKind(kind); - } function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195: + case 197: + case 187: + case 194: + case 198: + case 202: + case 200: + case 289: + case 288: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 @@ -8970,6 +9190,10 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -9196,7 +9420,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); } return res; } @@ -10987,9 +11211,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288: @@ -11169,7 +11395,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -11289,9 +11515,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } function token() { return currentToken; } @@ -11414,13 +11637,11 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -11468,7 +11689,8 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var reportAtCurrentPosition = token() === 1; + return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -11701,20 +11923,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -11920,12 +12142,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26)) { continue; @@ -11950,15 +12173,15 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); if (commaStart >= 0) { result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -12000,12 +12223,12 @@ var ts; var template = createNode(196); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -12100,7 +12323,7 @@ var ts; var result = createNode(273); nextToken(); fillSignature(56, 4 | 32, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159); node.typeName = parseIdentifierName(); @@ -12158,9 +12381,10 @@ var ts; return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || isStartOfType(); + token() === 57 || + isStartOfType(true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146); if (token() === 99) { node.name = createIdentifier(true); @@ -12176,37 +12400,33 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); + node.initializer = parseInitializer(true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56)) { + return true; } - else if (flags & 4) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); - if (backwardToken) { - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { if (parseExpected(19)) { @@ -12214,7 +12434,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -12278,7 +12498,7 @@ var ts; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -12410,7 +12630,7 @@ var ts; parseExpected(94); } fillSignature(36, 4, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -12424,16 +12644,9 @@ var ts; unaryMinusExpression.operator = 38; nextToken(); } - var expression; - switch (token()) { - case 9: - case 8: - expression = parseLiteralLikeNode(token()); - break; - case 101: - case 86: - expression = parseTokenNode(); - } + var expression = token() === 101 || token() === 86 + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -12466,6 +12679,7 @@ var ts; return parseJSDocNodeWithType(274); case 51: return parseJSDocNodeWithType(271); + case 13: case 9: case 8: case 101: @@ -12497,7 +12711,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119: case 136: @@ -12522,11 +12736,14 @@ var ts; case 86: case 134: case 39: + case 55: + case 51: + case 24: return true; case 38: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -12592,13 +12809,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -12758,11 +12974,16 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58) { if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { return undefined; } + if (inParameter && requireEqualsToken) { + var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } parseExpected(58); return parseAssignmentExpressionOrHigher(); @@ -12823,8 +13044,7 @@ var ts; var parameter = createNode(146, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); @@ -12931,8 +13151,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -12961,7 +13180,8 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { + if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { return undefined; } return node; @@ -13303,7 +13523,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { @@ -13320,12 +13541,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254); @@ -14204,7 +14424,7 @@ var ts; var node = createNode(176); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { @@ -14220,7 +14440,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingPattern() { @@ -14254,7 +14474,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -14418,7 +14638,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57)) { @@ -14427,20 +14648,13 @@ var ts; var decorator = createNode(147, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); + (list || (list = [])).push(decorator); } - return decorators; + return list && createNodeArray(list, listPos); } function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -14455,17 +14669,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } + (list || (list = [])).push(modifier); } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -14475,7 +14681,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -14970,9 +15175,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267, scanner.getTokenPos()); - parseExpected(17); + if (!parseExpected(17) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576, parseType); parseExpected(18); fixupParentReferences(result); @@ -15029,6 +15236,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; if (!isJsDocStart(content, start)) { @@ -15137,7 +15346,7 @@ var ts; } function createJSDocComment() { var result = createNode(275, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -15260,21 +15469,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { var isBracketed = parseOptional(21); @@ -15364,11 +15569,11 @@ var ts; var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(true); var result = createNode(277, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -15403,19 +15608,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285, start_3); } if (child.kind === 281) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -15429,7 +15633,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -15523,7 +15729,8 @@ var ts; if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name_8 = parseJSDocIdentifierName(); skipWhitespace(); @@ -15546,9 +15753,8 @@ var ts; var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -15640,7 +15846,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -16814,7 +17020,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; if (jsonConversionNotifier && (parentOption || knownOptions === knownRootOptions)) { @@ -16849,7 +17055,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); return null; case 9: if (!isDoubleQuotedString(valueExpression)) { @@ -16905,6 +17111,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; if (option.type === "list") { return ts.isArray(value); } @@ -17057,6 +17265,12 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } @@ -17080,7 +17294,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -17092,7 +17306,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -17101,7 +17315,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -17118,7 +17332,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -17180,7 +17394,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -17202,7 +17417,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -17356,6 +17572,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -17378,6 +17596,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -17414,7 +17634,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -17613,7 +17833,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -17716,12 +17936,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -17834,12 +18054,12 @@ var ts; var commonPrefix = getCommonPrefix(path, resolvedFileName); var current = path; while (true) { - var parent_4 = ts.getDirectoryPath(current); - if (parent_4 === current || directoryPathMap.has(parent_4)) { + var parent_3 = ts.getDirectoryPath(current); + if (parent_3 === current || directoryPathMap.has(parent_3)) { break; } - directoryPathMap.set(parent_4, result); - current = parent_4; + directoryPathMap.set(parent_3, result); + current = parent_3; if (current === commonPrefix) { break; } @@ -18018,7 +18238,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -18180,31 +18400,40 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -18247,9 +18476,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); @@ -18532,9 +18772,11 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { - symbol.declarations = []; + symbol.declarations = [node]; + } + else { + symbol.declarations.push(node); } - symbol.declarations.push(node); if (symbolFlags & 1952 && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } @@ -18598,17 +18840,8 @@ var ts; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; case 283: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (ts.isIdentifier(nameIdentifier)) { - nameFromParentNode = nameIdentifier.escapedText; - } - } - } - return nameFromParentNode; + var name_11 = ts.getNameOfJSDocTypedef(node); + return typeof name_11 !== "undefined" ? name_11.escapedText : undefined; } } function getDisplayName(node) { @@ -18809,7 +19042,7 @@ var ts; ts.forEachChild(node, bind, bindEach); } function bindChildrenWorker(node) { - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; @@ -19549,9 +19782,6 @@ var ts; lastContainer = next; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { case 233: return declareModuleMember(node, symbolFlags, symbolExcludes); @@ -19713,6 +19943,9 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & 8) { + symbol.parent = container.symbol; + } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { @@ -19870,7 +20103,7 @@ var ts; inStrictMode = saveInStrictMode; } function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { + if (!ts.hasJSDocNodes(node)) { return; } for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -20121,12 +20354,12 @@ var ts; return; } else { - var parent_5 = node.parent; - if (!ts.isExternalModule(parent_5)) { + var parent_4 = node.parent; + if (!ts.isExternalModule(parent_4)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_5.isDeclarationFile) { + if (!parent_4.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -21047,31 +21280,38 @@ var ts; return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = ts.createMap(); - var visitedSymbols = ts.createMap(); + var visitedTypes = []; + var visitedSymbols = []; return { walkType: function (type) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitType(type); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, walkSymbol: function (symbol) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitSymbol(symbol); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, }; function visitType(type) { if (!type) { return; } - var typeIdString = type.id.toString(); - if (visitedTypes.has(typeIdString)) { + if (visitedTypes[type.id]) { return; } - visitedTypes.set(typeIdString, type); + visitedTypes[type.id] = type; var shouldBail = visitSymbol(type.symbol); if (shouldBail) return; @@ -21104,23 +21344,15 @@ var ts; visitIndexedAccessType(type); } } - function visitTypeList(types) { - if (!types) { - return; - } - for (var i = 0; i < types.length; i++) { - visitType(types[i]); - } - } function visitTypeReference(type) { visitType(type.target); - visitTypeList(type.typeArguments); + ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { visitType(getConstraintFromTypeParameter(type)); } function visitUnionOrIntersectionType(type) { - visitTypeList(type.types); + ts.forEach(type.types, visitType); } function visitIndexType(type) { visitType(type.type); @@ -21140,7 +21372,7 @@ var ts; if (signature.typePredicate) { visitType(signature.typePredicate.type); } - visitTypeList(signature.typeParameters); + ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; visitSymbol(parameter); @@ -21150,8 +21382,8 @@ var ts; } function visitInterfaceType(interfaceT) { visitObjectType(interfaceT); - visitTypeList(interfaceT.typeParameters); - visitTypeList(getBaseTypes(interfaceT)); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); visitType(interfaceT.thisType); } function visitObjectType(type) { @@ -21177,11 +21409,11 @@ var ts; if (!symbol) { return; } - var symbolIdString = ts.getSymbolId(symbol).toString(); - if (visitedSymbols.has(symbolIdString)) { + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { return; } - visitedSymbols.set(symbolIdString, symbol); + visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { return true; } @@ -21243,6 +21475,7 @@ var ts; var enumCount = 0; var symbolInstantiationDepth = 0; var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -21395,12 +21628,13 @@ var ts; return tryFindAmbientModule(moduleName, false); }, getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + isArrayLikeType: isArrayLikeType, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, undefined, false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; @@ -21479,7 +21713,8 @@ var ts; var deferredUnusedIdentifierNodes; var flowLoopStart = 0; var flowLoopCount = 0; - var visitedFlowCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); var resolutionTargets = []; @@ -21494,8 +21729,8 @@ var ts; var flowLoopNodes = []; var flowLoopKeys = []; var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; @@ -21624,6 +21859,7 @@ var ts; })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; function getJsxNamespace() { @@ -21705,7 +21941,7 @@ var ts; } function cloneSymbol(symbol) { var result = createSymbol(symbol.flags, symbol.escapedName); - result.declarations = symbol.declarations.slice(0); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -21933,10 +22169,10 @@ var ts; }); } } - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; var result; var lastLocation; @@ -22092,10 +22328,16 @@ var ts; lastLocation = location; location = location.parent; } - if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 265); + if (lastLocation.commonJsModuleIndicator && name === "exports") { + return lastLocation.symbol; + } + } result = lookup(globals, name, meaning); } if (!result) { @@ -22207,15 +22449,15 @@ var ts; } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); - var parent_6 = errorLocation.parent; + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); + var parent_5 = errorLocation.parent; if (symbol) { - if (ts.isQualifiedName(parent_6)) { - ts.Debug.assert(parent_6.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); - var propName = parent_6.right.escapedText; + if (ts.isQualifiedName(parent_5)) { + ts.Debug.assert(parent_5.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent_5.right.escapedText; var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); if (propType) { - error(parent_6, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + error(parent_5, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); return true; } } @@ -22231,7 +22473,7 @@ var ts; error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -22241,14 +22483,14 @@ var ts; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -22276,11 +22518,17 @@ var ts; return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { + switch (node.kind) { + case 237: return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); + case 239: + return node.parent; + case 240: + return node.parent.parent; + case 242: + return node.parent.parent.parent; + default: + return undefined; } } function getDeclarationOfAliasSymbol(symbol) { @@ -22353,28 +22601,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { - var name_11 = specifier.propertyName || specifier.name; - if (name_11.escapedText) { + var name_12 = specifier.propertyName || specifier.name; + if (name_12.escapedText) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.escapedText); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_12.escapedText); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.escapedText); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_12.escapedText); } symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name_11.escapedText, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name_11.escapedText === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_12.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name_12.escapedText === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); + error(name_12, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_12)); } return symbol; } @@ -22490,7 +22738,7 @@ var ts; var symbol; if (name.kind === 71) { var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, true); if (!symbol) { return undefined; } @@ -22529,7 +22777,7 @@ var ts; undefined; } else { - ts.Debug.fail("Unknown entity name kind."); + ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -22577,13 +22825,13 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -22682,10 +22930,9 @@ var ts; moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || emptySymbols; function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 && ts.pushIfUnique(visitedSymbols, symbol))) { return; } - visitedSymbols.push(symbol); var symbols = ts.cloneMap(symbol.exports); var exportStars = symbol.exports.get("__export"); if (exportStars) { @@ -22824,55 +23071,51 @@ var ts; return rightMeaning === 107455 ? 107455 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { + var visitedSymbolTables = []; + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - visitedSymbolTables.push(symbols); var result = trySymbolTable(symbols); visitedSymbolTables.pop(); return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + function isUMDExportSymbol(symbol) { + return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.escapedName))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 - && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246) + && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; } - }); - } - } - if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { @@ -22975,14 +23218,7 @@ var ts; isDeclarationVisible(anyImportSyntax.parent)) { if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } @@ -23004,7 +23240,7 @@ var ts; meaning = 793064; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), @@ -23037,7 +23273,7 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(3, typeNode, sourceFile, writer); + printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; if (maxLength && result.length >= maxLength) { @@ -23122,8 +23358,8 @@ var ts; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 272) { - var name_12 = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name_12, undefined); + var name_13 = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name_13, undefined); } if (type.flags & (32)) { return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216)); @@ -23166,13 +23402,13 @@ var ts; return typeReferenceToTypeNode(type); } if (type.flags & 16384 || objectFlags & 3) { - var name_13 = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name_13, undefined); + var name_14 = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name_14, undefined); } if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { - var name_14 = symbolToTypeReferenceName(type.aliasSymbol); + var name_15 = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name_14, typeArgumentNodes); + return ts.createTypeReferenceNode(name_15, typeArgumentNodes); } if (type.flags & (65536 | 131072)) { var types = type.flags & 65536 ? formatUnionTypes(type.types) : type.types; @@ -23319,17 +23555,17 @@ var ts; var i = 0; var qualifiedName = void 0; if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { var start = i; - var parent_7 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_7); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var typeArgumentNodes_1 = typeArgumentSlice && ts.createNodeArray(typeArgumentSlice); - var namePart = symbolToTypeReferenceName(parent_7); + var namePart = symbolToTypeReferenceName(parent_6); (namePart.kind === 71 ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; if (qualifiedName) { ts.Debug.assert(!qualifiedName.right); @@ -23559,11 +23795,11 @@ var ts; var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_8) { - var parentChain = getSymbolChain(parent_8, getQualifiedLeftMeaning(meaning), false); + var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_7) { + var parentChain = getSymbolChain(parent_7, getQualifiedLeftMeaning(meaning), false); if (parentChain) { - parentSymbol = parent_8; + parentSymbol = parent_7; accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); } } @@ -23578,29 +23814,6 @@ var ts; } } } - function getNameOfSymbol(symbol, context) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - var name_15 = ts.getNameOfDeclaration(declaration); - if (name_15) { - return ts.declarationNameToString(name_15); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return ts.unescapeLeadingUnderscores(symbol.escapedName); - } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { return ts.usingSingleLineStringWriter(function (writer) { @@ -23658,9 +23871,9 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol) { + function getNameOfSymbol(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name_16 = ts.getNameOfDeclaration(declaration); @@ -23670,6 +23883,9 @@ var ts; if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); } + if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } switch (declaration.kind) { case 199: return "(Anonymous class)"; @@ -23678,6 +23894,12 @@ var ts; return "(Anonymous function)"; } } + if (symbol.syntheticLiteralTypeOrigin) { + var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { + return "\"" + ts.escapeString(stringValue, 34) + "\""; + } + } return ts.unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder() { @@ -23728,9 +23950,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_9 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_9) { - walkSymbol(parent_9, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -23775,9 +23997,9 @@ var ts; writeTypeReference(type, nextFlags); } else if (type.flags & 256 && !(type.flags & 65536)) { - var parent_10 = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent_10, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent_10) !== type) { + var parent_9 = getParentOfSymbol(type.symbol); + buildSymbolDisplay(parent_9, writer, enclosingDeclaration, 793064, 0, nextFlags); + if (getDeclaredTypeOfSymbol(parent_9) !== type) { writePunctuation(writer, 23); appendSymbolNameOnly(type.symbol, writer); } @@ -23874,15 +24096,15 @@ var ts; var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { - var length_3 = outerTypeParameters.length; - while (i < length_3) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { var start = i; - var parent_11 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_10 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_11); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_10); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_11, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_10, typeArguments, start, i, flags); writePunctuation(writer, 23); } } @@ -24349,12 +24571,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_12 = getDeclarationContainer(node); + var parent_11 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent_12.kind !== 265 && ts.isInAmbientContext(parent_12))) { - return isGlobalSourceFile(parent_12); + !(node.kind !== 237 && parent_11.kind !== 265 && ts.isInAmbientContext(parent_11))) { + return isGlobalSourceFile(parent_11); } - return isDeclarationVisible(parent_12); + return isDeclarationVisible(parent_11); case 149: case 148: case 153: @@ -24398,7 +24620,7 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node, false); } else if (node.parent.kind === 246) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); @@ -24412,13 +24634,11 @@ var ts; ts.forEach(declarations, function (declaration) { getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } + ts.pushIfUnique(result, resultNode); if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -24429,8 +24649,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_4 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_4; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -25041,34 +25261,48 @@ var ts; for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } + typeParameters = ts.appendIfUnique(typeParameters, tp); } return typeParameters; } - function appendOuterTypeParameters(typeParameters, node) { + function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; if (!node) { - return typeParameters; + return undefined; } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } + switch (node.kind) { + case 229: + case 199: + case 230: + case 155: + case 156: + case 150: + case 160: + case 161: + case 273: + case 228: + case 151: + case 186: + case 187: + case 231: + case 282: + case 172: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 172) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var thisType = includeThisTypes && + (node.kind === 229 || node.kind === 199 || node.kind === 230) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); + return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { var result; @@ -25116,7 +25350,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -25190,7 +25424,7 @@ var ts; var valueDecl = type.symbol.valueDeclaration; if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { + if (augTag && augTag.typeExpression && augTag.typeExpression.type) { baseType = getTypeFromTypeNode(augTag.typeExpression.type); } } @@ -25306,7 +25540,8 @@ var ts; var declaration = ts.find(symbol.declarations, function (d) { return d.kind === 283 || d.kind === 231; }); - var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + var typeNode = declaration.kind === 283 ? declaration.typeExpression : declaration.type; + var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -25640,7 +25875,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -25674,9 +25909,7 @@ var ts; if (!match) { return undefined; } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } + result = ts.appendIfUnique(result, match); } return result; } @@ -25852,7 +26085,11 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { + function addMemberForKeyType(t, propertySymbolOrIndex) { + var propertySymbol; + if (typeof propertySymbolOrIndex === "object") { + propertySymbol = propertySymbolOrIndex; + } var iterationMapper = createTypeMapper([typeParameter], [t]); var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; var propType = instantiateType(templateType, templateMapper); @@ -25867,6 +26104,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } + prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } else if (t.flags & 2) { @@ -25977,26 +26215,22 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getAllPossiblePropertiesOfType(type) { - if (type.flags & 65536) { - var props = ts.createSymbolTable(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var memberType = _a[_i]; - if (memberType.flags & 8190) { - continue; - } - for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { - var escapedName = _c[_b].escapedName; - if (!props.has(escapedName)) { - props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); - } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 65536)) { + return getPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var memberType = types_2[_i]; + for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); } } - return ts.arrayFrom(props.values()); - } - else { - return getPropertiesOfType(type); } + return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { return type.flags & 16384 ? getConstraintOfTypeParameter(type) : @@ -26058,8 +26292,8 @@ var ts; if (t.flags & 196608) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type_2 = types_2[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type_2 = types_3[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -26122,20 +26356,15 @@ var ts; var commonFlags = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var current = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var current = types_4[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } + props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | (!(modifiers & 24) ? 64 : 0) | (modifiers & 16 ? 128 : 0) | @@ -26261,12 +26490,7 @@ var ts; var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - if (!result) { - result = []; - } - result.push(tp); - } + result = ts.appendIfUnique(result, tp); }); return result; } @@ -26302,7 +26526,7 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512); return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { @@ -26352,11 +26576,10 @@ var ts; } return minTypeArgumentCount; } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { if (!typeArguments) { typeArguments = []; @@ -26388,7 +26611,7 @@ var ts; var param = declaration.parameters[i]; var paramSymbol = param.symbol; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -26576,8 +26799,8 @@ var ts; } return anyType; } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -26590,12 +26813,20 @@ var ts; return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); } function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } function getOrCreateTypeFromSignature(signature) { if (!signature.isolatedSignatureType) { @@ -26661,12 +26892,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_5 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_5) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_5 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -26683,8 +26914,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -26720,13 +26951,14 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var isJavascript = ts.isInJavaScriptFile(node); + if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, undefined, 1), minTypeArgumentCount, typeParameters.length); return unknownType; } - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -26742,7 +26974,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); } return instantiation; } @@ -26934,7 +27166,7 @@ var ts; return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); + return resolveName(undefined, name, meaning, diagnostic, name, false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -27080,6 +27312,20 @@ var ts; function containsType(types, type) { return binarySearchTypes(types, type) >= 0; } + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6368 && combined & 6368) { + return true; + } + combined |= t.flags; + if (combined & 6144 && combined & (32768 | 16777216)) { + return true; + } + } + return false; + } function addTypeToUnion(typeSet, type) { var flags = type.flags; if (flags & 65536) { @@ -27096,7 +27342,7 @@ var ts; if (!(flags & 2097152)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192)) { + else if (!(flags & 8192 || flags & 131072 && isEmptyIntersectionType(type))) { if (flags & 2) typeSet.containsString = true; if (flags & 4) @@ -27114,14 +27360,14 @@ var ts; } } function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -27129,8 +27375,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -27254,8 +27500,8 @@ var ts; } } function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; addTypeToIntersection(typeSet, type); } } @@ -27401,20 +27647,6 @@ var ts; } return anyType; } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - if (accessNode) { - if (!isTypeAssignableTo(indexType, getIndexType(type))) { - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); - return unknownType; - } - if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { - error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - } - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } function isGenericObjectType(type) { return type.flags & 540672 ? true : getObjectFlags(type) & 32 ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : @@ -27454,12 +27686,15 @@ var ts; getIntersectionType(stringIndexTypes) ]); } + if (isGenericMappedType(objectType)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } return undefined; } function getIndexedAccessType(objectType, indexType, accessNode) { - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { return objectType; @@ -27472,7 +27707,7 @@ var ts; return type; } var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + if (indexType.flags & 65536 && !(indexType.flags & 8)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -27548,7 +27783,10 @@ var ts; return mapType(right, function (t) { return getSpreadType(left, t); }); } if (right.flags & 16777216) { - return emptyObjectType; + return nonPrimitiveType; + } + if (right.flags & (136 | 84 | 262178 | 272)) { + return left; } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); @@ -27768,10 +28006,6 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } function makeUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -27790,19 +28024,15 @@ var ts; } function createTypeMapper(sources, targets) { ts.Debug.assert(targets === undefined || sources.length === targets.length); - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; } function createTypeEraser(sources) { return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; + return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -27812,18 +28042,11 @@ var ts; createInferenceContext(mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : mapper; } - function identityMapper(type) { - return type; - } function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; + return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; + return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { var result = createType(16384); @@ -27881,15 +28104,50 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } + if (symbol.isRestParameter) { + result.isRestParameter = symbol.isRestParameter; + } return result; } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (!typeParameters) { + var declaration_1 = symbol.declarations[0]; + var outerTypeParameters = getOuterTypeParameters(declaration_1, true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + outerTypeParameters; + links.typeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + var combinedMapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function isTypeParameterReferencedWithin(tp, node) { + return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); + function checkThis(node) { + return node.kind === 169 || ts.forEachChild(node, checkThis); + } + function checkIdentifier(node) { + return node.kind === 71 && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + } } function instantiateMappedType(type, mapper) { var constraintType = getConstraintTypeFromMappedType(type); @@ -27900,135 +28158,59 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); } return t; }); } } } - return instantiateMappedObjectType(type, mapper); + return instantiateAnonymousType(type, mapper); } function isMappableType(type) { return type.flags & (16384 | 32768 | 131072 | 524288); } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64, type.symbol); + if (type.objectFlags & 32) { + result.declaration = type.declaration; + } + result.target = type; + result.mapper = mapper; result.aliasSymbol = type.aliasSymbol; result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var d = typeParameters_1[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 273: - var func = node; - for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { - var p = _b[_a]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (type.objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } - return type; } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } return type; } function instantiateIndexInfo(info, mapper) { @@ -28039,6 +28221,7 @@ var ts; switch (node.kind) { case 186: case 187: + case 151: return isContextSensitiveFunctionLikeDeclaration(node); case 178: return ts.forEach(node.properties, isContextSensitive); @@ -28052,9 +28235,6 @@ var ts; (isContextSensitive(node.left) || isContextSensitive(node.right)); case 261: return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); case 185: return isContextSensitive(node.expression); case 254: @@ -28141,7 +28321,8 @@ var ts; if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0; } - if (source.typeParameters) { + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var result = -1; @@ -28384,6 +28565,13 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); var expandingFlags = 0; var overflow = false; var isIntersectionConstituent = false; @@ -28567,10 +28755,21 @@ var ts; } else { var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { - errorNode = prop.valueDeclaration; + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + if (ts.isIdentifier(propDeclaration.name)) { + suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } return { value: true }; @@ -28777,7 +28976,7 @@ var ts; } } else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); + var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { errorInfo = saveErrorInfo; @@ -28810,7 +29009,7 @@ var ts; } } else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); + var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { errorInfo = saveErrorInfo; @@ -28885,22 +29084,21 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + } + return 0; + } var result = -1; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 16777216) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 4194304)) { + if (!(targetProp.flags & 4194304)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { @@ -29172,9 +29370,10 @@ var ts; return type.flags & 16384 && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + return getObjectFlags(type) & 4 && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } - function getTypeReferenceId(type, typeParameters) { + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } var result = "" + type.target.id; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; @@ -29186,6 +29385,9 @@ var ts; } result += "=" + index; } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } else { result += "-" + t.id; } @@ -29351,8 +29553,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29388,7 +29590,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; + return !!(type.flags & 6368); } function isLiteralType(type) { return type.flags & 8 ? true : @@ -29416,8 +29618,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -29629,7 +29831,6 @@ var ts; function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; - context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -29667,7 +29868,7 @@ var ts; } function couldContainTypeVariables(type) { var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || + return !!(type.flags & (540672 | 262144) || objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || objectFlags & 32 || @@ -29721,18 +29922,18 @@ var ts; return inference.candidates && getUnionType(inference.candidates, true); } } - function isPossiblyAssignableTo(source, target) { + function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (!(targetProp.flags & (16777216 | 4194304))) { - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (requireOptionalProperties || !(targetProp.flags & 16777216)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return false; + return targetProp; } } } - return true; + return undefined; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } @@ -29808,6 +30009,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 262144 && target.flags & 262144) { + inferFromTypes(source.type, target.type); + } + else if (source.flags & 524288 && target.flags & 524288) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (target.flags & 196608) { var targetTypes = target.types; var typeVariableCount = 0; @@ -29829,7 +30037,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 196608) { + else if (source.flags & 65536) { var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { var sourceType = sourceTypes_3[_e]; @@ -29838,7 +30046,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 32768) { + if (source.flags & (32768 | 131072)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -29873,6 +30081,10 @@ var ts; return undefined; } function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } if (getObjectFlags(target) & 32) { var constraintType = getConstraintTypeFromMappedType(target); if (constraintType.flags & 262144) { @@ -29894,7 +30106,7 @@ var ts; return; } } - if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + if (!getUnmatchedProperty(source, target, false) || !getUnmatchedProperty(target, source, false)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0); inferFromSignatures(source, target, 1); @@ -29905,7 +30117,7 @@ var ts; var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -29951,8 +30163,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -30023,7 +30235,8 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -30187,8 +30400,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -30445,8 +30658,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30515,8 +30728,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -30565,69 +30778,87 @@ var ts; } return false; } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return unknownType; + } if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { return declaredType; } - var visitedFlowStart = visitedFlowCount; + var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; + sharedFlowCount = sharedFlowStart; var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { return declaredType; } return resultType; function getTypeAtFlowNode(flow) { + if (flowDepth === 2500) { + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return unknownType; + } + flowDepth++; while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; + var flags = flow.flags; + if (flags & 1024) { + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; } } } var type = void 0; - if (flow.flags & 4096) { + if (flags & 4096) { flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flow.flags & 2048) { + else if (flags & 2048) { flow = flow.antecedent; continue; } - else if (flow.flags & 16) { + else if (flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 96) { + else if (flags & 96) { type = getTypeAtFlowCondition(flow); } - else if (flow.flags & 128) { + else if (flags & 128) { type = getTypeAtSwitchClause(flow); } - else if (flow.flags & 12) { + else if (flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flow.flags & 4 ? + type = flags & 4 ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flow.flags & 256) { + else if (flags & 256) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 2) { + else if (flags & 2) { var container = flow.container; if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { flow = container.flowNode; @@ -30638,11 +30869,12 @@ var ts; else { type = convertAutoToAny(declaredType); } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; + if (flags & 1024) { + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; } + flowDepth--; return type; } } @@ -30671,30 +30903,32 @@ var ts; return undefined; } function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 84)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + return flowType; } - return flowType; } return undefined; } @@ -30740,9 +30974,7 @@ var ts; if (type === declaredType && declaredType === initialType) { return type; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -30789,9 +31021,7 @@ var ts; if (cached_1) { return cached_1; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); if (!isTypeSubsetOf(type, declaredType)) { subtypeReduction = true; } @@ -31565,7 +31795,8 @@ var ts; } } } - if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var inJs = ts.isInJavaScriptFile(func); + if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { var contextualType = getApparentTypeOfContextualType(containingLiteral); @@ -31584,10 +31815,18 @@ var ts; } return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; + var parent_12 = func.parent; + if (parent_12.kind === 194 && parent_12.operatorToken.kind === 58) { + var target = parent_12.left; if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); + var expression = target.expression; + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent_12); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); } } } @@ -31741,7 +31980,7 @@ var ts; else if (operator === 54) { var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left, true); } return type; } @@ -31787,16 +32026,10 @@ var ts; } return undefined; } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIndexTypeOfContextualType(arrayContextualType, 1) + || getIteratedTypeOrElementType(arrayContextualType, undefined, false, false, false)); } function getContextualTypeForConditionalOperand(node) { var conditional = node.parent; @@ -31870,15 +32103,20 @@ var ts; return getContextualTypeForObjectLiteralElement(parent); case 263: return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); + case 177: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } case 195: return getContextualTypeForConditionalOperand(node); case 205: ts.Debug.assert(parent.parent.kind === 196); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); + case 185: { + var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } case 256: return getContextualTypeForJsxExpression(parent); case 253: @@ -31941,8 +32179,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -31980,8 +32218,9 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elements.length; index++) { + var e = elements[index]; if (inDestructuringPattern && e.kind === 198) { var restArrayType = checkExpression(e.expression, checkMode); var restElementType = getIndexTypeOfType(restArrayType, 1) || @@ -31991,7 +32230,8 @@ var ts; } } else { - var type = checkExpressionForMutableLocation(e, checkMode); + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 198; @@ -32002,15 +32242,15 @@ var ts; type.pattern = node; return type; } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; + var contextualType_1 = getApparentTypeOfContextualType(node); + if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { + var pattern = contextualType_1.pattern; if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType_1.typeArguments[i]); } else { if (patternElement.kind !== 200) { @@ -32096,6 +32336,7 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = memberDecl.symbol; + var literalName = void 0; if (memberDecl.kind === 261 || memberDecl.kind === 262 || ts.isObjectLiteralMethod(memberDecl)) { @@ -32105,6 +32346,12 @@ var ts; } var type = void 0; if (memberDecl.kind === 261) { + if (memberDecl.name.kind === 144) { + var t = checkComputedPropertyName(memberDecl.name); + if (t.flags & 224) { + literalName = ts.escapeLeadingUnderscores("" + t.value); + } + } type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === 151) { @@ -32119,14 +32366,14 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.escapedName); + var prop = createSymbol(4 | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216; } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } @@ -32173,7 +32420,7 @@ var ts; ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); checkNodeDeferred(memberDecl); } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -32231,7 +32478,8 @@ var ts; } } function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + return !!(type.flags & (1 | 16777216) || + getFalsyFlags(type) & 7392 && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || type.flags & 32768 && !isGenericMappedType(type) || type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } @@ -32421,8 +32669,9 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + var isJavascript = ts.isInJavaScriptFile(node); + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0, isJavascript); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); @@ -32705,7 +32954,7 @@ var ts; checkJsxPreconditions(node); var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = true; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -32881,19 +33130,8 @@ var ts; } return unknownType; } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - } - markPropertyAsReferenced(prop); + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -32912,6 +33150,56 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + else if (valueDeclaration.kind === 229 && + node.parent.kind !== 159 && + !ts.isInAmbientContext(valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 149: + return true; + case 261: + return false; + default: + return ts.isPartOfExpression(node) ? false : "quit"; + } + }); + } + function isPropertyDeclaredInAncestorClass(prop) { + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + ts.Debug.assert(x.length === 1); + return x[0]; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 && !(containingType.flags & 8190)) { @@ -32924,8 +33212,8 @@ var ts; } } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + if (suggestion !== undefined) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -32937,7 +33225,7 @@ var ts; return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, undefined, name, function (symbols, name, meaning) { + var result = resolveNameHelper(location, name, meaning, undefined, name, false, function (symbols, name, meaning) { var symbol = getSymbol(symbols, name, meaning); if (symbol) { return symbol; @@ -32997,11 +33285,12 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { if (prop && noUnusedIdentifiers && (prop.flags & 106500) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8) + && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { if (ts.getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } @@ -33010,15 +33299,6 @@ var ts; } } } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 ? node.expression @@ -33209,7 +33489,6 @@ var ts; var argCount; var typeArguments; var callIsIncomplete; - var isDecorator; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; @@ -33231,7 +33510,6 @@ var ts; } } else if (node.kind === 147) { - isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, undefined, signature); } @@ -33280,7 +33558,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } - return getSignatureInstantiation(signature, getInferredTypes(context)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { @@ -33289,13 +33567,13 @@ var ts; inference.inferredType = undefined; } } - if (ts.isExpression(node)) { + if (node.kind !== 147) { var contextualType = getContextualType(node); if (contextualType) { var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); @@ -33715,8 +33993,9 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { candidateForTypeArgumentError = originalCandidate; break; @@ -33725,7 +34004,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { candidateForArgumentError = candidate; @@ -33831,11 +34110,6 @@ var ts; if (expressionType === unknownType) { return resolveErrorCall(node); } - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } if (isTypeAny(expressionType)) { if (node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -33847,6 +34121,11 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } var callSignatures = getSignaturesOfType(expressionType, 0); @@ -33960,8 +34239,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -33986,7 +34265,7 @@ var ts; case 250: return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } function getResolvedSignature(node, candidatesOutArray) { var links = getNodeLinks(node); @@ -34000,16 +34279,30 @@ var ts; return result; } function isJavaScriptConstructor(node) { - if (ts.isInJavaScriptFile(node)) { + if (node && ts.isInJavaScriptFile(node)) { if (ts.getJSDocClassTag(node)) return true; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; return symbol && symbol.members !== undefined; } return false; } + function getJavaScriptClassType(symbol) { + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + } + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + return getInferredClassType(symbol); + } + if (symbol.flags & 3) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + return getInferredClassType(valueType.symbol); + } + } + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -34038,13 +34331,11 @@ var ts; var funcSymbol = node.expression.kind === 71 ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { - return getInferredClassType(funcSymbol); + var type = funcSymbol && getJavaScriptClassType(funcSymbol); + if (type) { + return type; } - else if (noImplicitAny) { + if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -34105,7 +34396,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined, true); if (!resolvedRequire) { return true; } @@ -34211,7 +34502,7 @@ var ts; } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { var parameter = ts.lastOrUndefined(signature.parameters); - if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } @@ -34341,9 +34632,7 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } }); return aggregatedTypes; @@ -34387,9 +34676,7 @@ var ts; if (type.flags & 8192) { hasReturnOfTypeNever = true; } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } else { hasReturnWithNoExpression = true; @@ -34400,9 +34687,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } + ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } @@ -34655,8 +34940,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -35154,20 +35439,6 @@ var ts; var type2 = checkExpression(node.whenFalse, checkMode); return getBestChoiceType(type1, type2); } - function checkLiteralExpression(node) { - switch (node.kind) { - case 13: - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - checkGrammarNumericLiteral(node); - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } function checkTemplateExpression(node) { ts.forEach(node.templateSpans, function (templateSpan) { checkExpression(templateSpan.expression); @@ -35219,9 +35490,13 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode) { + function checkExpressionForMutableLocation(node, checkMode, contextualType) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); + return shouldWiden ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, checkMode) { if (node.name.kind === 144) { @@ -35289,12 +35564,9 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); - if (typecasts && typecasts.length) { - var cast_1 = typecasts[0]; - return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); - } + var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } @@ -35310,10 +35582,14 @@ var ts; return nullWideningType; case 13: case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101: + return trueType; case 86: - return checkLiteralExpression(node); + return falseType; case 196: return checkTemplateExpression(node); case 12: @@ -35862,7 +36138,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, ts.isInJavaScriptFile(typeArgumentNodes[i])); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -35930,6 +36206,10 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + if (accessNode.kind === 180 && ts.isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & 32 && objectType.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } return type; } if (getIndexInfoOfType(getApparentType(objectType), 1) && isTypeAssignableToKind(indexType, 84)) { @@ -36195,6 +36475,7 @@ var ts; switch (d.kind) { case 230: case 231: + case 283: return 2; case 233: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 @@ -36204,6 +36485,8 @@ var ts; case 232: return 2 | 1; case 237: + case 240: + case 239: var result_3 = 0; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); @@ -36393,8 +36676,11 @@ var ts; markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } function markEntityNameOrEntityExpressionAsReference(typeName) { - var rootName = typeName && getFirstIdentifier(typeName); - var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 71 ? 793064 : 1920) | 2097152; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 && symbolIsValue(rootSymbol) @@ -36500,22 +36786,12 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDoc(node) { - if (!ts.isInJavaScriptFile(node)) { - return; - } - ts.forEach(node.jsDoc, checkSourceElement); - } - function checkJSDocComment(node) { - if (node.tags) { - for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - checkSourceElement(tag); - } + function checkJSDocTypedefTag(node) { + if (!node.typeExpression) { + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } function checkFunctionOrMethodDeclaration(node) { - checkJSDoc(node); checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); @@ -36620,11 +36896,11 @@ var ts; !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name_27)) { - error(name_27, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name_27, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); } } }); @@ -36637,15 +36913,17 @@ var ts; } return false; } - function errorUnusedLocal(node, name) { + function errorUnusedLocal(declaration, name) { + var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + var declaration_2 = ts.getRootDeclaration(node.parent); + if ((declaration_2.kind === 226 && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 145) { return; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } function parameterNameStartsWithUnderscore(parameterName) { @@ -36661,14 +36939,14 @@ var ts; var member = _a[_i]; if (member.kind === 151 || member.kind === 149) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -36686,8 +36964,8 @@ var ts; } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -36700,7 +36978,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); } } } @@ -36711,7 +36989,14 @@ var ts; if (node.kind === 207) { checkGrammarStatementInAmbientContext(node); } - ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } if (node.locals) { registerForUnusedIdentifiersCheck(node); } @@ -36841,7 +37126,7 @@ var ts; if (symbol.flags & 1) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined, false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { @@ -36877,7 +37162,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -36938,7 +37223,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent_15); var name_29 = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_29)); - markPropertyAsReferenced(property); + markPropertyAsReferenced(property, undefined); if (parent_15.initializer && property) { checkPropertyAccessibility(parent_15, parent_15.initializer, parentType, property); } @@ -38343,8 +38628,8 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } } @@ -38371,7 +38656,7 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768); } } @@ -38388,7 +38673,7 @@ var ts; checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); } @@ -38421,9 +38706,12 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); + if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + if (modulekind >= ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -38453,7 +38741,7 @@ var ts; if (flags & (1920 | 64 | 384)) { return; } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); if (flags & 524288 && exportedDeclarationsCount <= 2) { return; } @@ -38468,15 +38756,24 @@ var ts; }); links.exportsChecked = true; } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } + } + function isNotAccessor(declaration) { + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var tags = _a[_i].tags; + ts.forEach(tags, checkSourceElement); + } + } var kind = node.kind; if (cancellationToken) { switch (kind) { @@ -38528,8 +38825,8 @@ var ts; case 168: case 170: return checkSourceElement(node.type); - case 275: - return checkJSDocComment(node); + case 283: + return checkJSDocTypedefTag(node); case 279: return checkSourceElement(node.typeExpression); case 273: @@ -38659,6 +38956,7 @@ var ts; ts.clear(potentialNewTargetCollisions); deferredNodes = []; deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalModule(node)) { @@ -38988,11 +39286,13 @@ var ts; return sig.thisParameter; } } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } case 169: - return getTypeFromTypeNode(node).symbol; + return getTypeFromThisTypeNode(node).symbol; + case 97: + return checkExpression(node).symbol; case 123: var constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === 152) { @@ -39006,13 +39306,17 @@ var ts; return resolveExternalModuleName(node, node); } case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - return getPropertyOfType(objectType, node.text); - } - break; + var objectType = ts.isElementAccessExpression(node.parent) + ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined + : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) + ? getTypeFromTypeNode(node.parent.parent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 79: + return getSymbolOfNode(node.parent); + default: + return undefined; } - return undefined; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 262) { @@ -39226,7 +39530,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + if (resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } else if (nodeLinks_1.flags & 131072) { @@ -39369,6 +39673,14 @@ var ts; return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { @@ -39452,7 +39764,7 @@ var ts; location = getDeclarationContainer(parent_16); } } - return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -39728,7 +40040,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly; var flags = 0; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -39750,12 +40062,6 @@ var ts; case 113: case 112: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } if (flags & 28) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } @@ -40247,7 +40553,7 @@ var ts; currentKind = SetAccessor; } else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name_35); if (effectiveName === undefined) { @@ -40507,7 +40813,7 @@ var ts; } } } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { checkESModuleMarker(node.name); } @@ -40522,8 +40828,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; if (!ts.isOmittedExpression(element)) { return checkESModuleMarker(element.name); } @@ -40538,8 +40844,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -40988,7 +41294,7 @@ var ts; || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node) + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } ts.updateParameter = updateParameter; @@ -41604,13 +41910,26 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanTokenOrBody, bodyOrUndefined) { + var equalsGreaterThanToken; + var body; + if (bodyOrUndefined === undefined) { + equalsGreaterThanToken = node.equalsGreaterThanToken; + body = ts.cast(equalsGreaterThanTokenOrBody, ts.isConciseBody); + } + else { + equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { + return n.kind === 36; + }); + body = bodyOrUndefined; + } return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node) + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } ts.updateArrowFunction = updateArrowFunction; @@ -41715,11 +42034,23 @@ var ts; return node; } ts.createConditional = createConditional; - function updateConditional(node, condition, whenTrue, whenFalse) { + function updateConditional(node, condition) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (args.length === 2) { + var whenTrue_1 = args[0], whenFalse_1 = args[1]; + return updateConditional(node, condition, node.questionToken, whenTrue_1, node.colonToken, whenFalse_1); + } + ts.Debug.assert(args.length === 4); + var questionToken = args[0], whenTrue = args[1], colonToken = args[2], whenFalse = args[3]; return node.condition !== condition + || node.questionToken !== questionToken || node.whenTrue !== whenTrue + || node.colonToken !== colonToken || node.whenFalse !== whenFalse - ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node) + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } ts.updateConditional = updateConditional; @@ -41737,6 +42068,30 @@ var ts; : node; } ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(14); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(15); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(16); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(13); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { var node = createSynthesizedNode(197); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 ? asteriskTokenOrExpression : undefined; @@ -42824,6 +43179,10 @@ var ts; return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction(undefined, undefined, param ? [param] : [], undefined, undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { return createBinary(left, 26, right); } @@ -43019,9 +43378,7 @@ var ts; var emitNode = getOrCreateEmitNode(node); for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { var helper = helpers_1[_i]; - if (!ts.contains(emitNode.helpers, helper)) { - emitNode.helpers = ts.append(emitNode.helpers, helper); - } + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); } } return node; @@ -43054,9 +43411,7 @@ var ts; var helper = sourceEmitHelpers[i]; if (predicate(helper)) { helpersRemoved++; - if (!ts.contains(targetEmitNode.helpers, helper)) { - targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); - } + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); } else if (helpersRemoved > 0) { sourceEmitHelpers[i - helpersRemoved] = helper; @@ -43774,11 +44129,9 @@ var ts; return recreateOuterExpressions(expression, mutableCall, 4); } } - else { - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { - return ts.setTextRange(ts.createParen(expression), expression); - } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 178 || leftmostExpressionKind === 186) { + return ts.setTextRange(ts.createParen(expression), expression); } return expression; } @@ -43914,9 +44267,17 @@ var ts; case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } + function isIgnorableParen(node) { + return node.kind === 185 + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { if (kinds === void 0) { kinds = 7; } - if (outerExpression && isOuterExpression(outerExpression, kinds)) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; @@ -43942,7 +44303,8 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var create = hasExportStarsToExportValues && moduleKind !== ts.ModuleKind.System - && moduleKind !== ts.ModuleKind.ES2015; + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; if (!create) { var helpers = ts.getEmitHelpers(node); if (helpers) { @@ -44372,7 +44734,7 @@ var ts; case 186: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -44388,7 +44750,7 @@ var ts; case 194: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 197: @@ -45142,7 +45504,7 @@ var ts; } else { var name_41 = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name_41.escapedText))) { + if (name_41 && !uniqueExports.get(ts.unescapeLeadingUnderscores(name_41.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name_41); uniqueExports.set(ts.unescapeLeadingUnderscores(name_41.escapedText), true); exportedNames = ts.append(exportedNames, name_41); @@ -45435,7 +45797,7 @@ var ts; } function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, false, propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), false, propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -45618,6 +45980,21 @@ var ts; return saveStateAndInvoke(node, sourceElementVisitorWorker); } function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 238: + case 237: + case 243: + case 244: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + return node; + } switch (node.kind) { case 238: return visitImportDeclaration(node); @@ -45628,7 +46005,7 @@ var ts; case 244: return visitExportDeclaration(node); default: - return visitorWorker(node); + ts.Debug.fail("Unhandled ellided statement"); } } function namespaceElementVisitor(node) { @@ -45778,7 +46155,7 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && - !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, 0, alwaysStrict)); } function shouldEmitDecorateCallForClass(node) { @@ -45842,8 +46219,10 @@ var ts; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -46449,7 +46828,7 @@ var ts; var name_44 = ts.getMutableClone(node); name_44.flags &= ~8; name_44.original = undefined; - name_44.parent = currentScope; + name_44.parent = ts.getParseTreeNode(currentScope); if (useFallback) { return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_44), ts.createLiteral("undefined")), name_44); } @@ -46579,7 +46958,7 @@ var ts; return updated; } function visitArrowFunction(node) { - var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context)); + var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } function visitParameter(node) { @@ -46715,6 +47094,7 @@ var ts; return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { @@ -47174,7 +47554,6 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var currentSourceFile; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var previousOnEmitNode = context.onEmitNode; @@ -47186,10 +47565,8 @@ var ts; if (node.isDeclarationFile) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -47232,7 +47609,7 @@ var ts; : ts.visitFunctionBody(node.body, visitor, context)); } function visitArrowFunction(node) { - return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 + return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -47522,8 +47899,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { - var e = elements_4[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; if (e.kind === 263) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -47541,7 +47918,7 @@ var ts; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } else { - chunkObject.push(e); + chunkObject.push(ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } } } @@ -47731,7 +48108,7 @@ var ts; function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; enclosingFunctionFlags = ts.getFunctionFlags(node); - var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); + var updated = ts.updateArrowFunction(node, node.modifiers, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } @@ -48556,58 +48933,12 @@ var ts; && node.kind === 219 && !node.expression; } - function isClassLikeVariableStatement(node) { - if (!ts.isVariableStatement(node)) - return false; - var variable = ts.singleOrUndefined(node.declarationList.declarations); - return variable - && variable.initializer - && ts.isIdentifier(variable.name) - && (ts.isClassLike(variable.initializer) - || (ts.isAssignmentExpression(variable.initializer) - && ts.isIdentifier(variable.initializer.left) - && ts.isClassLike(variable.initializer.right))); - } - function isTypeScriptClassWrapper(node) { - var call = ts.tryCast(node, ts.isCallExpression); - if (!call || ts.isParseTreeNode(call) || - ts.some(call.typeArguments) || - ts.some(call.arguments)) { - return false; - } - var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); - if (!func || ts.isParseTreeNode(func) || - ts.some(func.typeParameters) || - ts.some(func.parameters) || - func.type || - !func.body) { - return false; - } - var statements = func.body.statements; - if (statements.length < 2) { - return false; - } - var firstStatement = statements[0]; - if (ts.isParseTreeNode(firstStatement) || - !ts.isClassLike(firstStatement) && - !isClassLikeVariableStatement(firstStatement)) { - return false; - } - var lastStatement = ts.elementAt(statements, -1); - var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); - if (!returnStatement || - !returnStatement.expression || - !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { - return false; - } - return true; - } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 207))) || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) - || isTypeScriptClassWrapper(node); + || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -50087,7 +50418,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { - if (isTypeScriptClassWrapper(node)) { + if (ts.getEmitFlags(node) & 33554432) { return visitTypeScriptClassWrapper(node); } if (node.transformFlags & 64) { @@ -50096,7 +50427,7 @@ var ts; return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } function visitTypeScriptClassWrapper(node) { - var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); @@ -50516,7 +50847,6 @@ var ts; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; var renamedCatchVariables; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; @@ -50547,10 +50877,8 @@ var ts; if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -52294,6 +52622,7 @@ var ts; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var umdHeader = ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "factory")], undefined, ts.setTextRange(ts.createBlock([ ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([ ts.createVariableStatement(undefined, [ @@ -52304,13 +52633,13 @@ var ts; ]), ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, [ + ts.createStatement(ts.createCall(ts.createIdentifier("define"), undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), ts.createIdentifier("factory") - ])) + ]))) ]))) ], true), undefined)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ @@ -52375,17 +52704,20 @@ var ts; } function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - if (emitAsReturn) { - var statement = ts.createReturn(currentModuleInfo.exportEquals.expression); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 | 1536); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression)); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536); - statements.push(statement); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 | 1536); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536); + statements.push(statement); + } } } } @@ -52719,7 +53051,7 @@ var ts; return statements; } if (ts.hasModifier(decl, 1)) { - var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : decl.name; + var exportName = ts.hasModifier(decl, 512) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), decl); } if (decl.name) { @@ -53428,7 +53760,8 @@ var ts; } function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - return ts.createCall(exportFunction, undefined, [exportName, value]); + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536); + return ts.setCommentRange(ts.createCall(exportFunction, undefined, [exportName, value]), value); } function nestedElementVisitor(node) { switch (node.kind) { @@ -56559,8 +56892,13 @@ var ts; comments.reset(); setWriter(undefined); } + function emitIfPresent(node) { + if (node) { + emit(node); + } + } function emit(node) { - pipelineEmitWithNotification(3, node); + pipelineEmitWithNotification(4, node); } function emitIdentifierName(node) { pipelineEmitWithNotification(2, node); @@ -56598,7 +56936,8 @@ var ts; case 0: return pipelineEmitSourceFile(node); case 2: return pipelineEmitIdentifierName(node); case 1: return pipelineEmitExpression(node); - case 3: return pipelineEmitUnspecified(node); + case 3: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -56609,6 +56948,11 @@ var ts; ts.Debug.assertNode(node, ts.isIdentifier); emitIdentifier(node); } + function emitMappedTypeParameter(node) { + emit(node.name); + write(" in "); + emit(node.constraint); + } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { @@ -56952,9 +57296,9 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -56966,7 +57310,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); write(";"); } @@ -56974,7 +57318,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -56983,7 +57327,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); @@ -56992,9 +57336,9 @@ var ts; function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.asteriskToken, "*"); + emitIfPresent(node.asteriskToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -57064,9 +57408,8 @@ var ts; } function emitTypeLiteral(node) { write("{"); - if (node.members.length > 0) { - emitList(node, node.members, ts.getEmitFlags(node) & 1 ? 448 : 65); - } + var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; + emitList(node, node.members, flags | 262144); write("}"); } function emitArrayType(node) { @@ -57113,13 +57456,14 @@ var ts; writeLine(); increaseIndent(); } - writeIfPresent(node.readonlyToken, "readonly "); + if (node.readonlyToken) { + emit(node.readonlyToken); + write(" "); + } write("["); - emit(node.typeParameter.name); - write(" in "); - emit(node.typeParameter.constraint); + pipelineEmitWithNotification(3, node.typeParameter); write("]"); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); @@ -57159,36 +57503,25 @@ var ts; } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - var preferNewLine = node.multiLine ? 32768 : 0; - emitExpressionList(node, elements, 4466 | preferNewLine); - } + var preferNewLine = node.multiLine ? 32768 : 0; + emitExpressionList(node, elements, 4466 | preferNewLine); } function emitObjectLiteralExpression(node) { - var properties = node.properties; - if (properties.length === 0) { - write("{}"); + var indentedFlag = ts.getEmitFlags(node) & 65536; + if (indentedFlag) { + increaseIndent(); } - else { - var indentedFlag = ts.getEmitFlags(node) & 65536; - if (indentedFlag) { - increaseIndent(); - } - var preferNewLine = node.multiLine ? 32768 : 0; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; - emitList(node, properties, 978 | allowTrailingComma | preferNewLine); - if (indentedFlag) { - decreaseIndent(); - } + var preferNewLine = node.multiLine ? 32768 : 0; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 ? 32 : 0; + emitList(node, node.properties, 263122 | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); } } function emitPropertyAccessExpression(node) { @@ -57270,7 +57603,8 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); emitWithPrefix(": ", node.type); - write(" =>"); + write(" "); + emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { write("delete "); @@ -57325,12 +57659,12 @@ var ts; var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); increaseIndentIf(indentBeforeQuestion, " "); - write("?"); + emit(node.questionToken); increaseIndentIf(indentAfterQuestion, " "); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); increaseIndentIf(indentBeforeColon, " "); - write(":"); + emit(node.colonToken); increaseIndentIf(indentAfterColon, " "); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); @@ -57340,7 +57674,8 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write(node.asteriskToken ? "yield*" : "yield"); + write("yield"); + emit(node.asteriskToken); emitExpressionWithPrefix(" ", node.expression); } function emitSpreadExpression(node) { @@ -57375,27 +57710,16 @@ var ts; emit(node.literal); } function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - writeToken(17, node.pos, node); - write(" "); - writeToken(18, node.statements.end, node); - } - else { - writeToken(17, node.pos, node); - emitBlockStatements(node); - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18, node.statements.end, node); - } + writeToken(17, node.pos, node); + emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); + writeToken(18, node.statements.end, node); } - function emitBlockStatements(node) { - if (ts.getEmitFlags(node) & 1) { - emitList(node, node.statements, 384); - } - else { - emitList(node, node.statements, 65); - } + function emitBlockStatements(node, forceSingleLine) { + var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; + emitList(node, node.statements, format); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -57573,7 +57897,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.asteriskToken ? "function* " : "function "); + write("function"); + emitIfPresent(node.asteriskToken); + write(" "); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -57591,7 +57917,7 @@ var ts; if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -57601,7 +57927,7 @@ var ts; pushNameGenerationScope(); emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3, body, emitBlockCallback); + onEmitNode(4, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -57739,7 +58065,9 @@ var ts; } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - write(node.flags & 16 ? "namespace " : "module "); + if (~node.flags & 512) { + write(node.flags & 16 ? "namespace " : "module "); + } emit(node.name); var body = node.body; while (body.kind === 233) { @@ -57751,16 +58079,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isEmptyBlock(node)) { - write("{ }"); - } - else { - pushNameGenerationScope(); - write("{"); - emitBlockStatements(node); - write("}"); - popNameGenerationScope(); - } + pushNameGenerationScope(); + write("{"); + emitBlockStatements(node, isEmptyBlock(node)); + write("}"); + popNameGenerationScope(); } function emitCaseBlock(node) { writeToken(17, node.pos); @@ -57903,9 +58226,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { write("{"); - if (node.dotDotDotToken) { - write("..."); - } + emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); write("}"); } @@ -57936,13 +58257,12 @@ var ts; if (statements.length > 0) { emitTrailingCommentsOfPosition(statements.pos); } + var format = 81985; if (emitAsSingleStatement) { write(" "); - emit(statements[0]); - } - else { - emitList(parentNode, statements, 81985); + format &= ~(1 | 64); } + emitList(parentNode, statements, format); } function emitHeritageClause(node) { write(" "); @@ -58135,7 +58455,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emit(parameters[0]); + emitList(parentNode, parameters, 1360 & ~1024); } else { emitParameters(parentNode, parameters); @@ -58157,8 +58477,14 @@ var ts; if (isUndefined && format & 8192) { return; } - var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + var isEmpty = isUndefined || start >= children.length || count === 0; if (isEmpty && format & 16384) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } return; } if (format & 7680) { @@ -58171,7 +58497,7 @@ var ts; if (format & 1) { writeLine(); } - else if (format & 128) { + else if (format & 128 && !(format & 262144)) { write(" "); } } @@ -58230,7 +58556,7 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -58267,11 +58593,6 @@ var ts; write(text); } } - function writeIfPresent(node, text) { - if (node) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -58281,7 +58602,7 @@ var ts; if (onBeforeEmitToken) { onBeforeEmitToken(node); } - writeTokenText(node.kind); + write(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } @@ -58430,10 +58751,6 @@ var ts; && !ts.nodeIsSynthesized(node2) && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } - function isSingleLineEmptyBlock(block) { - return !block.multiLine - && isEmptyBlock(block); - } function isEmptyBlock(block) { return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); @@ -58677,6 +58994,8 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; @@ -58686,7 +59005,7 @@ var ts; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; @@ -58880,7 +59199,7 @@ var ts; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -58904,7 +59223,7 @@ var ts; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; + var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -58929,9 +59248,9 @@ var ts; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { - var start = diagnostic.start, length_6 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_6), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -58939,10 +59258,10 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += ts.sys.newLine; + output += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -58951,7 +59270,7 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); lineContent = lineContent.replace("\t", " "); output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; + output += lineContent + host.getNewLine(); output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; output += redForegroundEscapeSequence; if (i === firstLine) { @@ -58966,15 +59285,15 @@ var ts; output += lineContent.replace(/./g, "~"); } output += resetEscapeSequence; - output += ts.sys.newLine; + output += host.getNewLine(); } - output += ts.sys.newLine; + output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine; + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += host.getNewLine(); } return output; } @@ -59040,6 +59359,8 @@ var ts; ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); @@ -59089,12 +59410,11 @@ var ts; } if (!skipDefaultLib) { if (!options.lib) { - processRootFile(host.getDefaultLibFileName(options), true); + processRootFile(getDefaultLibraryFileName(), true); } else { - var libDirectory_1 = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(host.getDefaultLibFileName(options)); ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(libDirectory_1, libFileName), true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), true); }); } } @@ -59127,6 +59447,7 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, @@ -59350,7 +59671,7 @@ var ts; var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); @@ -59417,6 +59738,15 @@ var ts; function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (defaultLibraryPath && defaultLibraryPath.length !== 0) { + return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, !host.useCaseSensitiveFileNames()); + } + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), !host.useCaseSensitiveFileNames()) === 0; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } @@ -59531,9 +59861,7 @@ var ts; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - return ts.isSourceFileJavaScript(sourceFile) - ? ts.filter(diagnostics, shouldReportDiagnostic) - : diagnostics; + return ts.filter(diagnostics, shouldReportDiagnostic); }); } function shouldReportDiagnostic(diagnostic) { @@ -59749,16 +60077,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.text === b.text; - } - function getTextOfLiteral(literal) { - return literal.text; + return a.kind === 9 + ? b.kind === 9 && a.text === b.text + : b.kind === 71 && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -59874,8 +60201,8 @@ var ts; return sourceFileWithAddedExtension; } } - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, undefined); }, function (diagnostic) { + function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -59941,7 +60268,7 @@ var ts; } }); if (packageId) { - var packageIdKey = packageId.name + "@" + packageId.version; + var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -59988,7 +60315,7 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -60010,7 +60337,7 @@ var ts; var saveResolution = true; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { if (previousResolution) { @@ -60023,7 +60350,7 @@ var ts; saveResolution = false; } else { - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -60052,8 +60379,7 @@ var ts; function processImportedModules(file) { collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { - var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9; }); - var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); @@ -60064,13 +60390,19 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; } var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -60385,7 +60717,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -60393,6 +60725,17 @@ var ts; ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); return names; } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9) { + res.push(aug.text); + } + } + return res; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -60809,25 +61152,24 @@ var ts; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 || node.kind === 8) { - switch (node.parent.kind) { - case 149: - case 148: - case 261: - case 264: - case 151: - case 150: - case 153: - case 154: - case 233: - return ts.getNameOfDeclaration(node.parent) === node; - case 180: - return node.parent.argumentExpression === node; - case 144: - return true; - } + switch (node.parent.kind) { + case 149: + case 148: + case 261: + case 264: + case 151: + case 150: + case 153: + case 154: + case 233: + return ts.getNameOfDeclaration(node.parent) === node; + case 180: + return node.parent.argumentExpression === node; + case 144: + return true; + case 173: + return node.parent.parent.kind === 171; } - return false; } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; function isExpressionOfExternalModuleImportEqualsDeclaration(node) { @@ -60904,6 +61246,27 @@ var ts; return "alias"; case 283: return "type"; + case 194: + var kind = ts.getSpecialPropertyAssignmentKind(node); + var right = node.right; + switch (kind) { + case 0: + return ""; + case 1: + case 2: + var rightKind = getNodeKind(right); + return rightKind === "" ? "const" : rightKind; + case 3: + return "method"; + case 4: + return "property"; + case 5: + return ts.isFunctionExpression(right) ? "method" : "property"; + default: { + ts.assertTypeIsNever(kind); + return ""; + } + } default: return ""; } @@ -61091,7 +61454,7 @@ var ts; return undefined; } var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); + var listItemIndex = ts.indexOfNode(children, node); return { listItemIndex: listItemIndex, list: list @@ -62224,7 +62587,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_7 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -62232,8 +62595,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_7, classification: convertClassification(type) }); - lastEnd = start + length_7; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -63087,8 +63450,8 @@ var ts; continue; } var start = completePrefix.length; - var length_8 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -63348,7 +63711,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; if (sourceFile.languageVariant === 1 && location && location.parent && location.parent.kind === 252) { var tagName = location.parent.parent.openingElement.tagName; @@ -63370,14 +63733,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); + getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral); } if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); @@ -63395,7 +63758,7 @@ var ts; return; } uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, true); + var displayName = getCompletionEntryDisplayName(realName, target, true, false); if (displayName) { entries.push({ name: displayName, @@ -63406,8 +63769,8 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); if (!displayName) { return undefined; } @@ -63418,13 +63781,13 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { @@ -63471,7 +63834,7 @@ var ts; var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log, true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63495,7 +63858,7 @@ var ts; var type = typeChecker.getTypeAtLocation(node.expression); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false, typeChecker, target, log, true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -63526,7 +63889,7 @@ var ts; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } - else if (type.flags & 32) { + else if (type.flags & 32 && !(type.flags & 256)) { var name_56 = type.value; if (!uniques.has(name_56)) { uniques.set(name_56, true); @@ -63542,8 +63905,8 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_3 = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location_3 = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral_1) === entryName ? s : undefined; }); if (symbol) { var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { @@ -63572,7 +63935,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); - return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { @@ -63616,7 +63983,7 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -63686,6 +64053,7 @@ var ts; var semanticStart = ts.timestamp(); var isGlobalCompletion = false; var isMemberCompletion; + var allowStringLiteral = false; var isNewIdentifierLocation; var keywordFilters = 0; var symbols = []; @@ -63718,7 +64086,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 277: @@ -63983,6 +64351,7 @@ var ts; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { isMemberCompletion = true; + allowStringLiteral = true; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178) { @@ -63990,7 +64359,7 @@ var ts; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); existingMembers = objectLikeContainer.properties; } else { @@ -64419,7 +64788,7 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { var name = symbol.name; if (!name) return undefined; @@ -64429,11 +64798,11 @@ var ts; return undefined; } } - return getCompletionEntryDisplayName(name, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return undefined; + return allowStringLiteral ? JSON.stringify(name) : undefined; } return name; } @@ -64537,6 +64906,14 @@ var ts; return node.parent; } } + function getPropertiesForCompletion(type, checker) { + if (!(type.flags & 65536)) { + return checker.getPropertiesOfType(type); + } + var types = type.types; + var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 || checker.isArrayLikeType(memberType)); }); + return checker.getAllPossiblePropertiesOfTypes(filteredTypes); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -65085,11 +65462,10 @@ var ts; var bucket = getBucketForCompilationSettings(key, true); var entry = bucket.get(path); if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false, scriptKind); entry = { sourceFile: sourceFile, - languageServiceRefCount: 0, + languageServiceRefCount: 1, owners: [] }; bucket.set(path, entry); @@ -65098,9 +65474,9 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); } - } - if (acquiring) { - entry.languageServiceRefCount++; + if (acquiring) { + entry.languageServiceRefCount++; + } } return entry.sourceFile; } @@ -65265,7 +65641,6 @@ var ts; } } function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { @@ -65296,10 +65671,10 @@ var ts; searchForNamedImport(decl.exportClause); return; } - if (!decl.importClause) { + var importClause = decl.importClause; + if (!importClause) { return; } - var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { handleNamespaceImportLike(namedBindings.name); @@ -65315,39 +65690,42 @@ var ts; addSearch(name_60, defaultImportAlias); } if (!isForRename && exportKind === 1) { - ts.Debug.assert(exportName === "default"); searchForNamedImport(namedBindings); } } } function handleNamespaceImportLike(importName) { - if (exportKind === 2 && (!isForRename || importName.escapedText === exportName)) { + if (exportKind === 2 && (!isForRename || isNameMatch(importName.escapedText))) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) { - for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name_61 = element.name, propertyName = element.propertyName; - if ((propertyName || name_61).escapedText !== exportName) { - continue; - } - if (propertyName) { - singleReferences.push(propertyName); - if (!isForRename) { - addSearch(name_61, checker.getSymbolAtLocation(name_61)); - } - } - else { - var localSymbol = element.kind === 246 && element.propertyName - ? checker.getExportSpecifierLocalTargetSymbol(element) - : checker.getSymbolAtLocation(name_61); - addSearch(name_61, localSymbol); + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name_61 = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name_61).escapedText)) { + continue; + } + if (propertyName) { + singleReferences.push(propertyName); + if (!isForRename) { + addSearch(name_61, checker.getSymbolAtLocation(name_61)); } } + else { + var localSymbol = element.kind === 246 && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) + : checker.getSymbolAtLocation(name_61); + addSearch(name_61, localSymbol); + } } } + function isNameMatch(name) { + return name === exportSymbol.escapedName || exportKind !== 0 && name === "default"; + } } function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); @@ -65508,7 +65886,8 @@ var ts; function getExportAssignmentExport(ex) { var exportingModuleSymbol = ex.symbol.parent; ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + var exportKind = ex.isExportEquals ? 2 : 1; + return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -65537,7 +65916,8 @@ var ts; if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } - if (symbolName(importedSymbol) === symbol.escapedName) { + var importedName = symbolName(importedSymbol); + if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { return __assign({ kind: 0, symbol: importedSymbol }, isImport); } } @@ -65764,8 +66144,10 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 79 + || ts.isAnyDeclarationName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -65807,7 +66189,7 @@ var ts; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; - var writeAccess = isWriteAccess(node); + var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node), kind: writeAccess ? "writtenReference" : "reference", @@ -65825,20 +66207,8 @@ var ts; } return ts.createTextSpanFromBounds(start, end); } - function isWriteAccess(node) { - if (ts.isAnyDeclarationName(node)) { - return true; - } - var parent = node.parent; - switch (parent && parent.kind) { - case 193: - case 192: - return true; - case 194: - return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); - default: - return false; - } + function isWriteAccessForReference(node) { + return node.kind === 79 || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -66163,7 +66533,7 @@ var ts; return [{ definition: { type: "label", node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { - switch (node && node.kind) { + switch (node.kind) { case 71: return node.text.length === searchSymbolName.length; case 9: @@ -66171,6 +66541,8 @@ var ts; node.text.length === searchSymbolName.length; case 8: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 79: + return "default".length === searchSymbolName.length; default: return false; } @@ -66683,17 +67055,21 @@ var ts; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); + addRootSymbols(bindingElementPropertySymbol); } - for (var _i = 0, _a = checker.getRootSymbols(symbol); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); + addRootSymbols(symbol); + return result; + function addRootSymbols(sym) { + for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { + var rootSymbol = _a[_i]; + if (rootSymbol !== sym) { + result.push(rootSymbol); + } + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); + } } } - return result; } function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { if (!symbol) { @@ -66746,23 +67122,28 @@ var ts; } } var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); - if (bindingElementPropertySymbol && search.includes(bindingElementPropertySymbol)) { - return bindingElementPropertySymbol; - } - return ts.forEach(state.checker.getRootSymbols(referenceSymbol), function (rootSymbol) { - if (search.includes(rootSymbol)) { - return rootSymbol; - } - if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { - return undefined; + if (bindingElementPropertySymbol) { + var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); + if (fromBindingElement) + return fromBindingElement; + } + return findRootSymbol(referenceSymbol); + function findRootSymbol(sym) { + return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + if (search.includes(rootSymbol)) { + return rootSymbol; + } + if (rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + return undefined; + } + var result = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); + return ts.find(result, search.includes); } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); - return ts.find(result, search.includes); - } - return undefined; - }); + return undefined; + }); + } } function getNameFromObjectLiteralElement(node) { if (node.name.kind === 144) { @@ -67279,43 +67660,31 @@ var ts; if (!tokenAtPos || tokenStart < position) { return undefined; } - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 228: - case 151: - case 152: - case 229: - case 208: - break findOwner; - case 265: - return undefined; - case 233: - if (commentOwner.parent.kind === 233) { - return undefined; - } - break findOwner; - } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; } - if (!commentOwner || commentOwner.getStart() < position) { + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart() < position) { return undefined; } - var parameters = getParametersForJsDocOwningNode(commentOwner); var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; + if (parameters) { + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } } var preamble = "/**" + newLine + @@ -67327,18 +67696,38 @@ var ts; return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 208) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + function getCommentOwnerInfo(tokenAtPos) { + for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 228: + case 151: + case 152: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 229: + return { commentOwner: commentOwner }; + case 208: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 265: + return undefined; + case 233: + return commentOwner.parent.kind === 233 ? undefined : { commentOwner: commentOwner }; + case 194: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0) { + return undefined; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } } } - return ts.emptyArray; } function getParametersFromRightHandSideOfAssignment(rightHandSide) { while (rightHandSide.kind === 185) { @@ -67536,148 +67925,149 @@ var ts; return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { - if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { - return; - } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - if (patternMatcher.patternContainsDots) { - var containers = getContainers(declaration); - if (!containers) { - return true; - } - matches = patternMatcher.getMatches(containers, name); - if (!matches) { - return; - } - } - var fileName = sourceFile.fileName; - var matchKind = bestMatchKind(matches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); - } - } + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } - rawItems = ts.filter(rawItems, function (item) { - var decl = item.declaration; - if (decl.kind === 239 || decl.kind === 242 || decl.kind === 237) { - var importer = checker.getSymbolAtLocation(decl.name); - var imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName; - } - else { - return true; - } - }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); } - var items = ts.map(rawItems, createNavigateToItem); - return items; - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - if (!match.isCaseSensitive) { - return false; + return rawItems.map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); + if (!matches) { + return; + } + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (!shouldKeepItem(declaration, checker)) { + continue; + } + var containerMatches = matches; + if (patternMatcher.patternContainsDots) { + containerMatches = patternMatcher.getMatches(getContainers(declaration), name); + if (!containerMatches) { + continue; } } - return true; + var matchKind = bestMatchKind(containerMatches); + var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); + rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); } - function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name_64 = ts.getNameOfDeclaration(declaration); - if (name_64) { - var text = ts.getTextOfIdentifierOrLiteral(name_64); - if (text !== undefined) { - containers.unshift(text); - } - else if (name_64.kind === 144) { - return tryAddComputedPropertyName(name_64.expression, containers, true); - } - else { - return false; - } - } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 239: + case 242: + case 237: + var importer = checker.getSymbolAtLocation(declaration.name); + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: + return true; + } + } + function allMatchesAreCaseSensitive(matches) { + ts.Debug.assert(matches.length > 0); + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; + if (!match.isCaseSensitive) { + return false; } - return true; } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (text !== undefined) { - if (includeLastPortion) { + return true; + } + function tryAddSingleDeclarationName(declaration, containers) { + if (declaration) { + var name_64 = ts.getNameOfDeclaration(declaration); + if (name_64) { + var text = ts.getTextOfIdentifierOrLiteral(name_64); + if (text !== undefined) { containers.unshift(text); } - return true; - } - if (expression.kind === 179) { - var propertyAccess = expression; - if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); + else if (name_64.kind === 144) { + return tryAddComputedPropertyName(name_64.expression, containers, true); + } + else { + return false; } - return tryAddComputedPropertyName(propertyAccess.expression, containers, true); } - return false; } - function getContainers(declaration) { - var containers = []; - var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144) { - if (!tryAddComputedPropertyName(name.expression, containers, false)) { - return undefined; - } + return true; + } + function tryAddComputedPropertyName(expression, containers, includeLastPortion) { + var text = ts.getTextOfIdentifierOrLiteral(expression); + if (text !== undefined) { + if (includeLastPortion) { + containers.unshift(text); } - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; - } - declaration = ts.getContainerNode(declaration); + return true; + } + if (expression.kind === 179) { + var propertyAccess = expression; + if (includeLastPortion) { + containers.unshift(propertyAccess.name.text); } - return containers; + return tryAddComputedPropertyName(propertyAccess.expression, containers, true); } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } + return false; + } + function getContainers(declaration) { + var containers = []; + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { + return undefined; } - return bestMatchKind; } - function compareNavigateToItems(i1, i2) { - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + declaration = ts.getContainerNode(declaration); + while (declaration) { + if (!tryAddSingleDeclarationName(declaration, containers)) { + return undefined; + } + declaration = ts.getContainerNode(declaration); } - function createNavigateToItem(rawItem) { - var declaration = rawItem.declaration; - var container = ts.getContainerNode(declaration); - var containerName = container && ts.getNameOfDeclaration(container); - return { - name: rawItem.name, - kind: ts.getNodeKind(declaration), - kindModifiers: ts.getNodeModifiers(declaration), - matchKind: ts.PatternMatchKind[rawItem.matchKind], - isCaseSensitive: rawItem.isCaseSensitive, - fileName: rawItem.fileName, - textSpan: ts.createTextSpanFromNode(declaration), - containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" - }; + return containers; + } + function bestMatchKind(matches) { + ts.Debug.assert(matches.length > 0); + var bestMatchKind = ts.PatternMatchKind.camelCase; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; + var kind = match.kind; + if (kind < bestMatchKind) { + bestMatchKind = kind; + } } + return bestMatchKind; + } + function compareNavigateToItems(i1, i2) { + return i1.matchKind - i2.matchKind || + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" + }; } - NavigateTo.getNavigateToItems = getNavigateToItems; })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); var ts; @@ -67825,16 +68215,22 @@ var ts; break; case 176: case 226: - var decl = node; - var name_65 = decl.name; + var _d = node, name_65 = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name_65)) { addChildrenRecursively(name_65); } - else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { - addChildrenRecursively(decl.initializer); + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + addChildrenRecursively(initializer); + } + else { + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } } else { - addNodeWithRecursiveChild(decl, decl.initializer); + addNodeWithRecursiveChild(node, initializer); } break; case 187: @@ -67844,8 +68240,8 @@ var ts; break; case 232: startNode(node); - for (var _d = 0, _e = node.members; _d < _e.length; _d++) { - var member = _e[_d]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -67856,8 +68252,8 @@ var ts; case 199: case 230: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -67874,13 +68270,15 @@ var ts; addLeafNode(node); break; default: - ts.forEach(node.jsDoc, function (jsDoc) { - ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283) { - addLeafNode(tag); - } + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 283) { + addLeafNode(tag); + } + }); }); - }); + } ts.forEachChild(node, addChildrenRecursively); } } @@ -68193,7 +68591,14 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 186 || node.kind === 187 || node.kind === 199; + switch (node.kind) { + case 187: + case 186: + case 199: + return true; + default: + return false; + } } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); @@ -68203,11 +68608,15 @@ var ts; (function (OutliningElementsCollector) { var collapseText = "..."; var maxDepth = 20; + var defaultLabel = "#region"; + var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { var elements = []; var depth = 0; + var regions = []; walk(sourceFile); - return elements; + gatherRegions(); + return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { var span_13 = { @@ -68272,6 +68681,36 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187; } + function gatherRegions() { + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); + var comment = sourceFile.text.substring(currentLineStart, lineEnd); + var result = comment.match(regionMatch); + if (result && !ts.isInComment(sourceFile, currentLineStart)) { + if (!result[1]) { + var start = sourceFile.getFullText().indexOf("//", currentLineStart); + var textSpan = ts.createTextSpanFromBounds(start, lineEnd); + var region = { + textSpan: textSpan, + hintSpan: textSpan, + bannerText: result[2] || defaultLabel, + autoCollapse: false + }; + regions.push(region); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + elements.push(region); + } + } + } + } + } function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -68988,11 +69427,9 @@ var ts; return true; } token = nextToken(); - var i = 0; while (token !== 22 && token !== 1) { if (token === 9) { recordModuleName(); - i++; } token = nextToken(); } @@ -69132,10 +69569,16 @@ var ts; return ts.createTextSpan(start, width); } function nodeIsEligibleForRename(node) { - return node.kind === 71 || - node.kind === 9 || - ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - ts.isThis(node); + switch (node.kind) { + case 71: + case 9: + case 99: + return true; + case 8: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); @@ -69374,7 +69817,7 @@ var ts; if (isTypeParameterList) { isVariadic = false; prefixDisplayParts.push(ts.punctuationPart(27)); - var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { @@ -69509,7 +69952,7 @@ var ts; if (rootSymbolFlags & (98308 | 3)) { return "property"; } - ts.Debug.assert(!!(rootSymbolFlags & 8192)); + ts.Debug.assert(!!(rootSymbolFlags & (8192 | 16))); }); if (!unionPropertyKind) { var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); @@ -70035,7 +70478,6 @@ var ts; (function (formatting) { var standardScanner = ts.createScanner(5, false, 0); var jsxScanner = ts.createScanner(5, false, 1); - var scanner; var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -70045,9 +70487,8 @@ var ts; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); - function getFormattingScanner(text, languageVariant, startPos, endPos) { - ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); - scanner = languageVariant === 1 ? jsxScanner : standardScanner; + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 ? jsxScanner : standardScanner; scanner.setText(text); scanner.setTextPos(startPos); var wasNewLine = true; @@ -70056,38 +70497,28 @@ var ts; var savedPos; var lastScanAction; var lastTokenInfo; - return { + var res = cb({ advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, - close: function () { - ts.Debug.assert(scanner !== undefined); - lastTokenInfo = undefined; - scanner.setText(undefined); - scanner = undefined; - } - }; + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; function advance() { - ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - if (trailingTrivia) { - ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4; - } - else { - wasNewLine = false; - } + wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4; } - leadingTrivia = undefined; - trailingTrivia = undefined; - if (!isStarted) { + else { scanner.scan(); } + leadingTrivia = undefined; + trailingTrivia = undefined; var pos = scanner.getStartPos(); while (pos < endPos) { var t = scanner.getToken(); @@ -70101,23 +70532,18 @@ var ts; kind: t }; pos = scanner.getStartPos(); - if (!leadingTrivia) { - leadingTrivia = []; - } - leadingTrivia.push(item); + leadingTrivia = ts.append(leadingTrivia, item); } savedPos = scanner.getStartPos(); } function shouldRescanGreaterThanToken(node) { - if (node) { - switch (node.kind) { - case 31: - case 66: - case 67: - case 47: - case 46: - return true; - } + switch (node.kind) { + case 31: + case 66: + case 67: + case 47: + case 46: + return true; } return false; } @@ -70128,13 +70554,13 @@ var ts; case 251: case 252: case 250: - return node.kind === 71; + return ts.isKeyword(node.kind) || node.kind === 71; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 10; + return node.kind === 10; } function shouldRescanSlashToken(container) { return container.kind === 12; @@ -70147,14 +70573,7 @@ var ts; return t === 41 || t === 63; } function readTokenInfo(n) { - ts.Debug.assert(scanner !== undefined); - if (!isOnToken()) { - return { - leadingTrivia: leadingTrivia, - trailingTrivia: undefined, - token: undefined - }; - } + ts.Debug.assert(isOnToken()); var expectedScanAction = shouldRescanGreaterThanToken(n) ? 1 : shouldRescanSlashToken(n) @@ -70174,32 +70593,7 @@ var ts; scanner.setTextPos(savedPos); scanner.scan(); } - var currentToken = scanner.getToken(); - if (expectedScanAction === 1 && currentToken === 29) { - currentToken = scanner.reScanGreaterToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 1; - } - else if (expectedScanAction === 2 && startsWithSlashToken(currentToken)) { - currentToken = scanner.reScanSlashToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 2; - } - else if (expectedScanAction === 3 && currentToken === 18) { - currentToken = scanner.reScanTemplateToken(); - lastScanAction = 3; - } - else if (expectedScanAction === 4 && currentToken === 71) { - currentToken = scanner.scanJsxIdentifier(); - lastScanAction = 4; - } - else if (expectedScanAction === 5) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5; - } - else { - lastScanAction = 0; - } + var currentToken = getNextToken(n, expectedScanAction); var token = { pos: scanner.getStartPos(), end: scanner.getTextPos(), @@ -70230,8 +70624,46 @@ var ts; lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0; + switch (expectedScanAction) { + case 1: + if (token === 29) { + lastScanAction = 1; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2: + if (startsWithSlashToken(token)) { + lastScanAction = 2; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3: + if (token === 18) { + lastScanAction = 3; + return scanner.reScanTemplateToken(); + } + break; + case 4: + lastScanAction = 4; + return scanner.scanJsxIdentifier(); + case 5: + lastScanAction = 5; + return scanner.reScanJsxToken(); + case 0: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } function isOnToken() { - ts.Debug.assert(scanner !== undefined); var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); return startPos < endPos && current !== 1 && !ts.isTrivia(current); @@ -70360,11 +70792,6 @@ var ts; this.Operation = Operation; this.Flag = Flag; } - Rule.prototype.toString = function () { - return "[desc=" + this.Descriptor + "," + - "operation=" + this.Operation + "," + - "flag=" + this.Flag + "]"; - }; return Rule; }()); formatting.Rule = Rule; @@ -70683,16 +71110,16 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - } - Rules.prototype.getRuleName = function (rule) { - var o = this; - for (var name_66 in o) { - if (o[name_66] === rule) { - return name_66; + if (ts.Debug.isDebugging) { + var o = this; + for (var name_66 in o) { + var rule = o[name_66]; + if (rule instanceof formatting.Rule) { + rule.debugName = name_66; + } } } - throw new Error("Unknown rule"); - }; + } Rules.IsOptionEnabled = function (optionName) { return function (context) { return context.options && context.options.hasOwnProperty(optionName) && !!context.options[optionName]; }; }; @@ -70831,8 +71258,7 @@ var ts; return true; case 207: { var blockParent = context.currentTokenParent.parent; - if (blockParent.kind !== 187 && - blockParent.kind !== 186) { + if (!blockParent || blockParent.kind !== 187 && blockParent.kind !== 186) { return true; } } @@ -71242,15 +71668,9 @@ var ts; var RulesProvider = (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); this.rulesMap = formatting.RulesMap.create(activeRules); } - RulesProvider.prototype.getRuleName = function (rule) { - return this.globalRules.getRuleName(rule); - }; - RulesProvider.prototype.getRuleByName = function (name) { - return this.globalRules[name]; - }; RulesProvider.prototype.getRulesMap = function () { return this.rulesMap; }; @@ -71443,7 +71863,7 @@ var ts; } function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { @@ -71458,7 +71878,7 @@ var ts; } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); @@ -71484,7 +71904,6 @@ var ts; trimTrailingWhitespacesForRemainingRange(); } } - formattingScanner.close(); return edits; function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || @@ -71681,6 +72100,7 @@ var ts; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; @@ -72474,6 +72894,8 @@ var ts; case 241: case 246: case 242: + case 261: + case 149: return true; } return false; @@ -72518,15 +72940,21 @@ var ts; var textChanges; (function (textChanges) { function getPos(n) { - return n["__pos"]; + var result = n["__pos"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); n["__pos"] = pos; } function getEnd(n) { - return n["__end"]; + var result = n["__end"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); n["__end"] = end; } var Position; @@ -72573,7 +73001,8 @@ var ts; if (startLine === fullStartLine) { return position === Position.Start ? start : fullStart; } - var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + 1, sourceFile); + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } @@ -72599,9 +73028,6 @@ var ts; } return s; } - function getNewlineKind(context) { - return context.newLineCharacter === "\n" ? 1 : 0; - } var ChangeTracker = (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -72610,8 +73036,8 @@ var ts; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } - ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.rulesProvider); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -72637,7 +73063,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(node); + var index = ts.indexOfNode(containingList, node); if (index < 0) { return this; } @@ -72752,7 +73178,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(after); + var index = ts.indexOfNode(containingList, after); if (index < 0) { return this; } @@ -72915,10 +73341,9 @@ var ts; var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); - printer.writeNode(3, node, sourceFile, writer); + printer.writeNode(4, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - textChanges.getNonformattedText = getNonformattedText; function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { @@ -72929,7 +73354,6 @@ var ts; var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } - textChanges.applyFormatting = applyFormatting; function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -72943,13 +73367,10 @@ var ts; } function assignPositionsToNode(node) { var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); - var newNode = ts.nodeIsSynthesized(visited) - ? visited - : (Proxy.prototype = visited, new Proxy()); + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); newNode.end = getEnd(node); return newNode; - function Proxy() { } } function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); @@ -73082,7 +73503,15 @@ var ts; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); if (actions && actions.length > 0) { - allActions = allActions.concat(actions); + for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { + var action = actions_1[_i]; + if (action === undefined) { + context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); + } + else { + allActions.push(action); + } + } } }); return allActions; @@ -73111,6 +73540,10 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextLength(context) { + return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + } + ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); var ts; (function (ts) { @@ -73129,7 +73562,7 @@ var ts; var leftText = qualifiedName.left.getText(sourceFile); var rightText = qualifiedName.right.getText(sourceFile); var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); return [{ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), @@ -73258,7 +73691,7 @@ var ts; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), @@ -73273,7 +73706,7 @@ var ts; return actions; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), @@ -73299,7 +73732,7 @@ var ts; } typeNode = typeNode || ts.createKeywordTypeNode(119); var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); (actions || (actions = [])).push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), @@ -73309,7 +73742,7 @@ var ts; var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), @@ -73322,7 +73755,7 @@ var ts; if (token.parent.parent.kind === 181) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? @@ -73453,7 +73886,7 @@ var ts; } } } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); changeTracker.deleteNode(sourceFile, superCall); return [{ @@ -73485,7 +73918,7 @@ var ts; if (token.kind !== 123) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var superCall = ts.createStatement(ts.createCall(ts.createSuper(), undefined, ts.emptyArray)); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); return [{ @@ -73518,7 +73951,7 @@ var ts; if (!(extendsToken && extendsToken.kind === 85)) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108)); for (var i = 1; i < heritageClauses.length; i++) { var keywordToken = heritageClauses[i].getFirstToken(); @@ -73547,7 +73980,7 @@ var ts; if (token.kind !== 71) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), @@ -73563,8 +73996,8 @@ var ts; (function (codefix) { codefix.registerCodeFix({ errorCodes: [ - ts.Diagnostics._0_is_declared_but_never_used.code, - ts.Diagnostics.Property_0_is_declared_but_never_used.code + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code ], getCodeActions: function (context) { var sourceFile = context.sourceFile; @@ -73700,19 +74133,19 @@ var ts; } } function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); } function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteRange(sourceFile, range)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); } function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeInList(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); } function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeRange(sourceFile, start, end)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); } function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { return { @@ -73735,11 +74168,30 @@ var ts; function getActionsForJSDocTypes(context) { var sourceFile = context.sourceFile; var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); - var decl = ts.findAncestor(node, function (n) { return n.kind === 226; }); + var decl = ts.findAncestor(node, function (n) { + return n.kind === 202 || + n.kind === 155 || + n.kind === 156 || + n.kind === 228 || + n.kind === 153 || + n.kind === 157 || + n.kind === 172 || + n.kind === 151 || + n.kind === 150 || + n.kind === 146 || + n.kind === 149 || + n.kind === 148 || + n.kind === 154 || + n.kind === 231 || + n.kind === 184 || + n.kind === 226; + }); if (!decl) return; var checker = context.program.getTypeChecker(); var jsdocType = decl.type; + if (!jsdocType) + return; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; @@ -73918,28 +74370,21 @@ var ts; if (cached) { return cached; } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); - } - } + var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); cachedImportDeclarations[moduleSymbolId] = existingDeclarations; return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238) { - return node; - } - if (node.kind === 237) { - return node; - } - node = node.parent; + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238: + return parent; + case 248: + return parent.parent; + default: + return undefined; } - return undefined; } } function getUniqueSymbolId(symbol) { @@ -74281,7 +74726,7 @@ var ts; } } function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + return ts.textChanges.ChangeTracker.fromContext(context); } function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { return { @@ -74361,7 +74806,7 @@ var ts; (function (codefix) { function newNodesToChanges(newNodes, insertAfter, context) { var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { var newNode = newNodes_1[_i]; changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); @@ -74587,7 +75032,7 @@ var ts; return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { @@ -74616,7 +75061,9 @@ var ts; deleteCallback(); } return { - edits: changeTracker.getChanges() + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined, }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } @@ -74754,7 +75201,7 @@ var ts; }; refactor.registerRefactor(extractMethod); function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -74767,11 +75214,11 @@ var ts; var usedNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var extr = extractions_1[_i]; - if (extr.errors && extr.errors.length) { + var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; + if (errors.length) { continue; } - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); if (!usedNames.has(description)) { usedNames.set(description, true); actions.push({ @@ -74792,16 +75239,13 @@ var ts; }]; } function getEditsForAction(context, actionName) { - var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); var index = +parsedIndexMatch[1]; ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - var extractions = getPossibleExtractions(targetRange, context, index); - ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); - return ({ edits: extractions[0].changes }); + return getExtractionAtIndex(targetRange, context, index); } var Messages; (function (Messages) { @@ -74830,9 +75274,12 @@ var ts; RangeFacts[RangeFacts["IsAsyncFunction"] = 4] = "IsAsyncFunction"; RangeFacts[RangeFacts["UsesThis"] = 8] = "UsesThis"; RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; - })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + })(RangeFacts || (RangeFacts = {})); function getRangeToExtract(sourceFile, span) { - var length = span.length || 0; + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + } var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, false), sourceFile, span); var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); var declarations = []; @@ -74875,18 +75322,13 @@ var ts; if (errors) { return { errors: errors }; } - var range = ts.isStatement(start) - ? [start] - : start.parent && start.parent.kind === 210 - ? [start.parent] - : start; - return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; } function createErrorResult(sourceFile, start, length, message) { return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; } function checkRootNode(node) { - if (ts.isIdentifier(node)) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } return undefined; @@ -74923,7 +75365,7 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; } if (ts.isInAmbientContext(nodeToCheck)) { @@ -74979,39 +75421,26 @@ var ts; return false; } var savedPermittedJumps = permittedJumps; - if (node.parent) { - switch (node.parent.kind) { - case 211: - if (node.parent.thenStatement === node || node.parent.elseStatement === node) { - permittedJumps = 0; - } - break; - case 224: - if (node.parent.tryBlock === node) { - permittedJumps = 0; - } - else if (node.parent.finallyBlock === node) { - permittedJumps = 4; - } - break; - case 260: - if (node.parent.block === node) { - permittedJumps = 0; - } - break; - case 257: - if (node.expression !== node) { - permittedJumps |= 1; - } - break; - default: - if (ts.isIterationStatement(node.parent, false)) { - if (node.parent.statement === node) { - permittedJumps |= 1 | 2; - } - } - break; - } + switch (node.kind) { + case 211: + permittedJumps = 0; + break; + case 224: + permittedJumps = 0; + break; + case 207: + if (node.parent && node.parent.kind === 224 && node.finallyBlock === node) { + permittedJumps = 4; + } + break; + case 257: + permittedJumps |= 1; + break; + default: + if (ts.isIterationStatement(node, false)) { + permittedJumps |= 1 | 2; + } + break; } switch (node.kind) { case 169: @@ -75036,7 +75465,7 @@ var ts; } } else { - if (!(permittedJumps & (218 ? 1 : 2))) { + if (!(permittedJumps & (node.kind === 218 ? 1 : 2))) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } @@ -75065,6 +75494,15 @@ var ts; } } extractMethod_1.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isPartOfExpression(node)) { + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } function isValidExtractionTarget(node) { return (node.kind === 228) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); } @@ -75091,9 +75529,21 @@ var ts; } return scopes; } - extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; - function getPossibleExtractions(targetRange, context, requestedChangesIndex) { - if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; + ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + } + extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + return scopes.map(function (scope, i) { + return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + }); + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; if (targetRange === undefined) { return undefined; @@ -75103,86 +75553,62 @@ var ts; return undefined; } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; - context.cancellationToken.throwIfCancellationRequested(); - if (requestedChangesIndex !== undefined) { - if (errorsPerScope[requestedChangesIndex].length) { - return undefined; - } - return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; - } - else { - return scopes.map(function (scope, i) { - var errors = errorsPerScope[i]; - if (errors.length) { - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - errors: errors - }; - } - return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; - }); - } + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getDescriptionForScope(scope) { - if (ts.isFunctionLike(scope)) { - switch (scope.kind) { - case 152: - return "constructor"; - case 186: - return scope.name - ? "function expression " + scope.name.getText() - : "anonymous function expression"; - case 228: - return "function " + scope.name.getText(); - case 187: - return "arrow function"; - case 151: - return "method " + scope.name.getText(); - case 153: - return "get " + scope.name.getText(); - case 154: - return "set " + scope.name.getText(); - } - } - else if (ts.isModuleBlock(scope)) { - return "namespace " + scope.parent.name.getText(); - } - else if (ts.isClassLike(scope)) { - return scope.kind === 229 - ? "class " + scope.name.text - : scope.name.text - ? "class expression " + scope.name.text - : "anonymous class expression"; - } - else if (ts.isSourceFile(scope)) { - return "file '" + scope.fileName + "'"; - } - else { - return "unknown"; + return ts.isFunctionLikeDeclaration(scope) + ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? "method in " + getDescriptionForClassLikeDeclaration(scope) + : "function in " + getDescriptionForModuleLikeDeclaration(scope); + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 152: + return "constructor"; + case 186: + return scope.name + ? "function expression '" + scope.name.text + "'" + : "anonymous function expression"; + case 228: + return "function '" + scope.name.text + "'"; + case 187: + return "arrow function"; + case 151: + return "method '" + scope.name.getText(); + case 153: + return "'get " + scope.name.getText() + "'"; + case 154: + return "'set " + scope.name.getText() + "'"; + default: + ts.Debug.assertNever(scope); } } - function getUniqueName(isNameOkay) { + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 229 + ? "class '" + scope.name.text + "'" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 234 + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? "module scope" : "global scope"; + } + function getUniqueName(fileText) { var functionNameText = "newFunction"; - if (isNameOkay(functionNameText)) { - return functionNameText; - } - var i = 1; - while (!isNameOkay(functionNameText = "newFunction_" + i)) { - i++; + for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { + functionNameText = "newFunction_" + i; } return functionNameText; } function extractFunctionInScope(node, scope, _a, range, context) { - var usagesInScope = _a.usages, substitutions = _a.substitutions; + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); var file = scope.getSourceFile(); - var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var functionNameText = getUniqueName(file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var functionReference = ts.createIdentifier(functionNameText); var returnType = undefined; var parameters = []; var callArguments = []; @@ -75201,11 +75627,19 @@ var ts; } callArguments.push(ts.createIdentifier(name)); }); + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, undefined); }) + : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); returnType = checker.typeToTypeNode(contextualType); } - var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; var newFunction; if (ts.isClassLike(scope)) { var modifiers = isJS ? [] : [ts.createToken(112)]; @@ -75215,15 +75649,23 @@ var ts; if (range.facts & RangeFacts.IsAsyncFunction) { modifiers.push(ts.createToken(120)); } - newFunction = ts.createMethod(undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, [], parameters, returnType, body); + newFunction = ts.createMethod(undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, undefined, typeParameters, parameters, returnType, body); } else { - newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, [], parameters, returnType, body); + newFunction = ts.createFunctionDeclaration(undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var newNodes = []; - var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, undefined, callArguments); + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, callArguments); if (range.facts & RangeFacts.IsGenerator) { call = ts.createYield(ts.createToken(39), call); } @@ -75244,6 +75686,9 @@ var ts; } else { newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } } } else { @@ -75273,63 +75718,152 @@ var ts; else { changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); } - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - changes: changeTracker.getChanges() - }; - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); - } - function generateReturnValueProperty() { - return "__return"; - } - function transformFunctionBody(body) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; - } - var returnValueProperty; - var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - if (writes || substitutions.size) { - var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (assignments.length === 1) { - rewrittenStatements.push(ts.createReturn(assignments[0].name)); - } - else { - rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); - } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getRenameLocation(edits, renameFilename, functionNameText) { + var delta = 0; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { + var change = textChanges_2[_b]; + var span_17 = change.span, newText = change.newText; + var index = newText.indexOf(functionNameText); + if (index !== -1) { + return span_17.start + delta + index; + } + delta += newText.length - span_17.length; + } + } + throw new Error(); + } + function getFirstDeclaration(type) { + var firstDeclaration = undefined; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + if (declaration1) { + if (declaration2) { + var positionDiff = declaration1.pos - declaration2.pos; + if (positionDiff !== 0) { + return positionDiff; } - return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; } else { - return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; - } - function visitor(node) { - if (node.kind === 219 && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = generateReturnValueProperty(); - } - assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); - } - if (assignments.length === 1) { - return ts.createReturn(assignments[0].name); - } - else { - return ts.createReturn(ts.createObjectLiteral(assignments)); + return 1; + } + } + else if (declaration2) { + return -1; + } + var name1 = type1.symbol ? type1.symbol.getName() : ""; + var name2 = type2.symbol ? type2.symbol.getName() : ""; + var nameDiff = ts.compareStrings(name1, name2); + if (nameDiff !== 0) { + return nameDiff; + } + return type1.id - type2.id; + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, writes, substitutions, hasReturn) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + return { body: ts.createBlock(body.statements, true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !hasReturn && ts.isStatement(body)) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 219 && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); } else { - var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return ts.createReturn(ts.createObjectLiteral(assignments)); } } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } } } - extractMethod_1.extractFunctionInScope = extractFunctionInScope; + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLike(scope)) { + var body = scope.body; + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertTypeIsNever(scope); + } + return ts.emptyArray; + } + function getNodeToInsertBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + }); + } + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + } function isReadonlyArray(v) { return ts.isArray(v); } @@ -75343,21 +75877,50 @@ var ts; Usage[Usage["Read"] = 1] = "Read"; Usage[Usage["Write"] = 2] = "Write"; })(Usage || (Usage = {})); - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); var usagesPerScope = []; var substitutionsPerScope = []; var errorsPerScope = []; var visibleDeclarationsInExtractedRange = []; for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { var _ = scopes_1[_i]; - usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); errorsPerScope.push([]); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { + for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + ts.Debug.assert(i_1 === scopes.length); + } var _loop_8 = function (i) { var hasWrite = false; var readonlyClassPropertyWrite = undefined; @@ -75375,7 +75938,7 @@ var ts; errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); } }; for (var i = 0; i < scopes.length; i++) { @@ -75385,8 +75948,35 @@ var ts; ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function hasTypeParameters(node) { + return ts.isDeclarationWithTypeParameters(node) && + node.typeParameters !== undefined && + node.typeParameters.length > 0; + } + function isInGenericContext(node) { + for (; node; node = node.parent) { + if (hasTypeParameters(node)) { + return true; + } + } + return false; + } + function recordTypeParameterUsages(type) { + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.flags & 16384) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } if (ts.isDeclaration(node) && node.symbol) { visibleDeclarationsInExtractedRange.push(node.symbol); } @@ -75428,7 +76018,9 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = checker.getSymbolAtLocation(identifier); + var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); if (!symbol) { return undefined; } @@ -75452,7 +76044,7 @@ var ts; if (!declInFile) { return undefined; } - if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { return undefined; } if (targetRange.facts & RangeFacts.IsGenerator && usage === 2) { @@ -75473,7 +76065,9 @@ var ts; substitutionsPerScope[i].set(symbolId, substitution); } else if (isTypeName) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + if (!(symbol.flags & 262144)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } } else { usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); @@ -76059,6 +76653,10 @@ var ts; } } break; + case 194: + if (ts.getSpecialPropertyAssignmentKind(node) !== 0) { + addDeclaration(node); + } default: ts.forEachChild(node, visit); } @@ -76366,7 +76964,7 @@ var ts; oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || oldSettings.baseUrl !== newSettings.baseUrl || !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); var compilerHost = { @@ -76495,17 +77093,17 @@ var ts; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); - return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } function getSemanticDiagnostics(fileName) { synchronizeHostData(); var targetSourceFile = getValidSourceFile(fileName); var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { - return semanticDiagnostics; + return semanticDiagnostics.slice(); } var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); - return ts.concatenate(semanticDiagnostics, declarationDiagnostics); + return semanticDiagnostics.concat(declarationDiagnostics); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); @@ -76534,7 +77132,7 @@ var ts; return undefined; } var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { switch (node.kind) { case 71: @@ -76567,6 +77165,20 @@ var ts; tags: displayPartsDocumentationsAndKind.tags }; } + function getSymbolAtLocationForQuickInfo(node, checker) { + if ((ts.isIdentifier(node) || ts.isStringLiteral(node)) + && ts.isPropertyAssignment(node.parent) + && node.parent.name === node) { + var type = checker.getContextualType(node.parent.parent); + if (type) { + var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; + } + } + } + return checker.getSymbolAtLocation(node); + } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); @@ -76624,7 +77236,19 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + var sourceFiles = []; + if (options && options.isForRename) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + sourceFiles.push(sourceFile); + } + } + } + else { + sourceFiles = program.getSourceFiles().slice(); + } + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); @@ -76929,7 +77553,7 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: host.getNewLine(), + newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), rulesProvider: getRuleProvider(formatOptions), cancellationToken: cancellationToken }; @@ -77008,7 +77632,7 @@ var ts; nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } ts.forEachChild(node, walk); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; ts.forEachChild(jsDoc, walk); @@ -77570,8 +78194,8 @@ var ts; { start: start, end: end, text: text, code: code, category: category, source: source }; } function allEditsBeforePos(edits, pos) { - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var edit = edits_1[_i]; + for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) { + var edit = edits_2[_i]; if (ts.textSpanEnd(edit.span) >= pos) { return false; } @@ -78052,7 +78676,7 @@ var ts; }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = []; + var diags = server.emptyArray; if (!isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { diags = project.getLanguageService().getSemanticDiagnostics(file); } @@ -78740,12 +79364,12 @@ var ts; return undefined; } if (simplifiedResult) { - var span_17 = helpItems.applicableSpan; + var span_18 = helpItems.applicableSpan; return { items: helpItems.items, applicableSpan: { - start: scriptInfo.positionToLineOffset(span_17.start), - end: scriptInfo.positionToLineOffset(span_17.start + span_17.length) + start: scriptInfo.positionToLineOffset(span_18.start), + end: scriptInfo.positionToLineOffset(span_18.start + span_18.length) }, selectedItemIndex: helpItems.selectedItemIndex, argumentIndex: helpItems.argumentIndex, @@ -78947,7 +79571,7 @@ var ts; var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var _b = this.extractPositionAndRange(args, scriptInfo), position = _b.position, textRange = _b.textRange; - var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + var result = project.getLanguageService().getEditsForRefactor(file, args.formatOptions ? server.convertFormatOptions(args.formatOptions) : this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); if (result === undefined) { return { edits: [] @@ -79051,6 +79675,9 @@ var ts; return; } var fileNamesInProject = fileNames.filter(function (value) { return value.indexOf("lib.d.ts") < 0; }); + if (fileNamesInProject.length === 0) { + return; + } var highPriorityFiles = []; var mediumPriorityFiles = []; var lowPriorityFiles = []; @@ -79065,7 +79692,7 @@ var ts; else { var info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isScriptOpen()) { - if (fileNameInProject.indexOf(".d.ts") > 0) { + if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) { veryLowPriorityFiles.push(fileNameInProject); } else { @@ -79077,11 +79704,9 @@ var ts; } } } - fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); - if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); - this.updateErrorCheck(next, checkList, delay, false); - } + var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles); + var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); }); + this.updateErrorCheck(next, checkList, delay, false); }; Session.prototype.getCanonicalFileName = function (fileName) { var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); @@ -80019,16 +80644,18 @@ var ts; }()); server.TextStorage = TextStorage; var ScriptInfo = (function () { - function ScriptInfo(host, fileName, scriptKind, hasMixedContent) { + function ScriptInfo(host, fileName, scriptKind, hasMixedContent, isDynamic) { if (hasMixedContent === void 0) { hasMixedContent = false; } + if (isDynamic === void 0) { isDynamic = false; } this.host = host; this.fileName = fileName; this.scriptKind = scriptKind; this.hasMixedContent = hasMixedContent; + this.isDynamic = isDynamic; this.containingProjects = []; this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); this.textStorage = new TextStorage(host, fileName); - if (hasMixedContent) { + if (hasMixedContent || isDynamic) { this.textStorage.reload(""); } this.scriptKind = scriptKind @@ -80045,7 +80672,7 @@ var ts; }; ScriptInfo.prototype.close = function () { this.isOpen = false; - this.textStorage.useText(this.hasMixedContent ? "" : undefined); + this.textStorage.useText(this.hasMixedContent || this.isDynamic ? "" : undefined); this.markContainingProjectsAsDirty(); }; ScriptInfo.prototype.getSnapshot = function () { @@ -80154,7 +80781,7 @@ var ts; this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; ScriptInfo.prototype.reloadFromFile = function (tempFileName) { - if (this.hasMixedContent) { + if (this.hasMixedContent || this.isDynamic) { this.reload(""); } else { @@ -80490,7 +81117,7 @@ var ts; var server; (function (server) { function shouldEmitFile(scriptInfo) { - return !scriptInfo.hasMixedContent; + return !scriptInfo.hasMixedContent && !scriptInfo.isDynamic; } server.shouldEmitFile = shouldEmitFile; var BuilderFileInfo = (function () { @@ -80618,7 +81245,7 @@ var ts; }; NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { var info = this.getOrCreateFileInfo(scriptInfo.path); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; if (info.updateShapeSignature()) { var options = this.project.getCompilerOptions(); if (options && (options.out || options.outFile)) { @@ -80715,7 +81342,7 @@ var ts; }; ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { this.ensureProjectDependencyGraphUpToDate(); - var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var singleFileResult = scriptInfo.hasMixedContent || scriptInfo.isDynamic ? [] : [scriptInfo.fileName]; var fileInfo = this.getFileInfo(scriptInfo.path); if (!fileInfo || !fileInfo.updateShapeSignature()) { return singleFileResult; @@ -81178,24 +81805,23 @@ var ts; var file = changedFiles_1[_i]; this.cachedUnresolvedImportsPerFile.remove(file); } - var unresolvedImports; - if (hasChanges || changedFiles.length) { - var result = []; - for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { - var sourceFile = _b[_a]; - this.extractUnresolvedImportsFromSourceFile(sourceFile, result); - } - this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); - } - unresolvedImports = this.lastCachedUnresolvedImportsList; - var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); - if (this.setTypings(cachedTypings)) { - hasChanges = this.updateGraphWorker() || hasChanges; - } if (this.languageServiceEnabled) { + if (hasChanges || changedFiles.length) { + var result = []; + for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) { + var sourceFile = _b[_a]; + this.extractUnresolvedImportsFromSourceFile(sourceFile, result); + } + this.lastCachedUnresolvedImportsList = server.toDeduplicatedSortedArray(result); + } + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } this.builder.onProjectUpdateGraph(); } else { + this.lastCachedUnresolvedImportsList = undefined; this.builder.clear(); } if (hasChanges) { @@ -81338,7 +81964,8 @@ var ts; return { info: info, projectErrors: this.getGlobalProjectErrors() }; } var lastReportedFileNames_1 = this.lastReportedFileNames; - var currentFiles_1 = ts.arrayToSet(this.getFileNames()); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles)); var added_1 = []; var removed_1 = []; var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; @@ -81358,7 +81985,8 @@ var ts; } else { var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToSet(projectFileNames); + var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); }); + this.lastReportedFileNames = ts.arrayToSet(projectFileNames.concat(externalFiles)); this.lastReportedVersion = this.projectStructureVersion; return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; } @@ -81526,8 +82154,11 @@ var ts; } if (this.projectService.globalPlugins) { var _loop_10 = function (globalPluginName) { + if (!globalPluginName) + return "continue"; if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; + this_2.projectService.logger.info("Loading global plugin " + globalPluginName); this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; var this_2 = this; @@ -81539,6 +82170,7 @@ var ts; }; ConfiguredProject.prototype.enablePlugin = function (pluginConfigEntry, searchPaths) { var _this = this; + this.projectService.logger.info("Enabling plugin " + pluginConfigEntry.name + " from candidate paths: " + searchPaths.join(",")); var log = function (message) { _this.projectService.logger.info(message); }; @@ -81550,7 +82182,7 @@ var ts; return; } } - this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name + " anywhere in paths: " + searchPaths.join(",")); + this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name); }; ConfiguredProject.prototype.enableProxy = function (pluginModuleFactory, configEntry) { try { @@ -81566,7 +82198,16 @@ var ts; serverHost: this.projectService.host }; var pluginModule = pluginModuleFactory({ typescript: ts }); - this.languageService = pluginModule.create(info); + var newLS = pluginModule.create(info); + for (var _i = 0, _a = Object.keys(this.languageService); _i < _a.length; _i++) { + var k = _a[_i]; + if (!(k in newLS)) { + this.projectService.logger.info("Plugin activation warning: Missing proxied method " + k + " in created LS. Patching."); + newLS[k] = this.languageService[k]; + } + } + this.projectService.logger.info("Plugin validation succeded"); + this.languageService = newLS; this.plugins.push(pluginModule); } catch (e) { @@ -81595,6 +82236,9 @@ var ts; } catch (e) { _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + if (e.stack) { + _this.projectService.logger.info(e.stack); + } } })); }; @@ -81830,11 +82474,13 @@ var ts; getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, + isDynamicFile: function (x) { return x[0] === "^"; }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, - hasMixedContent: function (x) { return x.hasMixedContent; } + hasMixedContent: function (x) { return x.hasMixedContent; }, + isDynamicFile: function (x) { return x.fileName[0] === "^"; }, }; function findProjectByName(projectName, projects) { for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { @@ -82488,7 +83134,8 @@ var ts; var _this = this; var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); - this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); + var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); + this.addFilesToProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors); project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); if (!sizeLimitExceeded) { this.watchConfigDirectoryForProject(project, projectOptions); @@ -82509,15 +83156,16 @@ var ts; var errors; for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { var f = files_4[_i]; - var rootFilename = propertyReader.getFileName(f); + var rootFileName = propertyReader.getFileName(f); var scriptKind = propertyReader.getScriptKind(f); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - if (this.host.fileExists(rootFilename)) { - var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName === rootFilename, undefined, scriptKind, hasMixedContent); + var isDynamicFile = propertyReader.isDynamicFile(f); + if (isDynamicFile || this.host.fileExists(rootFileName)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFileName), clientFileName === rootFileName, undefined, scriptKind, hasMixedContent, isDynamicFile); project.addRoot(info); } else { - (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFileName)); } } project.setProjectErrors(ts.concatenate(configFileErrors, errors)); @@ -82545,7 +83193,8 @@ var ts; for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { var f = newUncheckedFiles_1[_i]; var newRootFile = propertyReader.getFileName(f); - if (!this.host.fileExists(newRootFile)) { + var isDynamic = propertyReader.isDynamicFile(f); + if (!isDynamic && !this.host.fileExists(newRootFile)) { (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); continue; } @@ -82556,7 +83205,7 @@ var ts; if (!scriptInfo) { var scriptKind = propertyReader.getScriptKind(f); var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent, isDynamic); } } newRootScriptInfos.push(scriptInfo); @@ -82695,16 +83344,16 @@ var ts; }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; - if (!info.hasMixedContent) { + if (!info.hasMixedContent && !info.isDynamic) { var fileName_3 = info.fileName; info.setWatcher(this.host.watchFile(fileName_3, function (_) { return _this.onSourceFileChanged(fileName_3); })); } }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, isDynamic) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { - if (openedByClient || this.host.fileExists(fileName)) { - info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent); + if (openedByClient || isDynamic || this.host.fileExists(fileName)) { + info = new server.ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, isDynamic); this.filenameToScriptInfo.set(info.path, info); if (openedByClient) { if (fileContent === undefined) { @@ -82853,7 +83502,7 @@ var ts; for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { var file = openFiles_1[_i]; var scriptInfo = this.getScriptInfo(file.fileName); - ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen()); + ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } @@ -82891,7 +83540,9 @@ var ts; var configuredProject = this.findConfiguredProjectByProjectName(configFile); if (configuredProject && configuredProject.deleteOpenRef() === 0) { this.removeProject(configuredProject); + return true; } + return false; }; ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { if (suppressRefresh === void 0) { suppressRefresh = false; } diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index dd56f51d4ac86..b6598e9f61734 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -446,6 +446,9 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -458,7 +461,7 @@ declare namespace ts { type EqualsToken = Token; type AsteriskToken = Token; type EqualsGreaterThanToken = Token; - type EndOfFileToken = Token; + type EndOfFileToken = Token & JSDocContainer; type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; @@ -500,6 +503,7 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; + parent?: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { @@ -510,16 +514,18 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends NamedDeclaration { + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type?: TypeNode; + type: TypeNode | undefined; } - interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.CallSignature; } - interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; @@ -535,7 +541,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends NamedDeclaration { + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -552,14 +558,14 @@ declare namespace ts { name: BindingName; initializer?: Expression; } - interface PropertySignature extends TypeElement { + interface PropertySignature extends TypeElement, JSDocContainer { kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } - interface PropertyDeclaration extends ClassElement { + interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; questionToken?: QuestionToken; name: PropertyName; @@ -571,27 +577,30 @@ declare namespace ts { name?: PropertyName; } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; - interface PropertyAssignment extends ObjectLiteralElement { + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.PropertyAssignment; name: PropertyName; questionToken?: QuestionToken; initializer: Expression; } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } - interface SpreadAssignment extends ObjectLiteralElement { + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.SpreadAssignment; expression: Expression; } interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name?: DeclarationName; + name: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -619,7 +628,7 @@ declare namespace ts { * - MethodDeclaration * - AccessorDeclaration */ - interface FunctionLikeDeclarationBase extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; @@ -632,16 +641,16 @@ declare namespace ts { name?: Identifier; body?: FunctionBody; } - interface MethodSignature extends SignatureDeclaration, TypeElement { + interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -651,20 +660,20 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; } @@ -678,10 +687,10 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclaration { + interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { + interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.ConstructorType; } type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; @@ -692,6 +701,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; + parent?: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -736,7 +746,6 @@ declare namespace ts { } interface MappedTypeNode extends TypeNode, Declaration { kind: SyntaxKind.MappedType; - parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; typeParameter: TypeParameterDeclaration; questionToken?: QuestionToken; @@ -744,7 +753,7 @@ declare namespace ts { } interface LiteralTypeNode extends TypeNode { kind: SyntaxKind.LiteralType; - literal: Expression; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; } interface StringLiteral extends LiteralExpression { kind: SyntaxKind.StringLiteral; @@ -879,12 +888,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -930,7 +939,7 @@ declare namespace ts { expression: Expression; literal: TemplateMiddle | TemplateTail; } - interface ParenthesizedExpression extends PrimaryExpression { + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } @@ -940,6 +949,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; + parent?: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1107,11 +1117,11 @@ declare namespace ts { kind: SyntaxKind.Block; statements: NodeArray; } - interface VariableStatement extends Statement { + interface VariableStatement extends Statement, JSDocContainer { kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } - interface ExpressionStatement extends Statement { + interface ExpressionStatement extends Statement, JSDocContainer { kind: SyntaxKind.ExpressionStatement; expression: Expression; } @@ -1192,7 +1202,7 @@ declare namespace ts { statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { + interface LabeledStatement extends Statement, JSDocContainer { kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; @@ -1214,19 +1224,21 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; - interface ClassLikeDeclaration extends NamedDeclaration { + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.ClassDeclaration; name?: Identifier; } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { kind: SyntaxKind.ClassExpression; } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; @@ -1236,7 +1248,7 @@ declare namespace ts { name?: PropertyName; questionToken?: QuestionToken; } - interface InterfaceDeclaration extends DeclarationStatement { + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; @@ -1249,26 +1261,26 @@ declare namespace ts { token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } - interface TypeAliasDeclaration extends DeclarationStatement { + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends NamedDeclaration { + interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; initializer?: Expression; } - interface EnumDeclaration extends DeclarationStatement { + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleName = Identifier | StringLiteral; type ModuleBody = NamespaceBody | JSDocNamespaceBody; - interface ModuleDeclaration extends DeclarationStatement { + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; parent?: ModuleBody | SourceFile; name: ModuleName; @@ -1295,7 +1307,7 @@ declare namespace ts { * - import x = require("mod"); * - import x = M.x; */ - interface ImportEqualsDeclaration extends DeclarationStatement { + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; parent?: SourceFile | ModuleBlock; name: Identifier; @@ -1407,7 +1419,7 @@ declare namespace ts { kind: SyntaxKind.JSDocOptionalType; type: TypeNode; } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { kind: SyntaxKind.JSDocFunctionType; } interface JSDocVariadicType extends JSDocType { @@ -1417,6 +1429,7 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; + parent?: HasJSDoc; tags: NodeArray | undefined; comment: string | undefined; } @@ -1472,7 +1485,6 @@ declare namespace ts { interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: ReadonlyArray; - jsDocTypeTag?: JSDocTypeTag; /** If true, then this type literal represents an *array* of its type. */ isArrayType?: boolean; } @@ -1547,10 +1559,10 @@ declare namespace ts { endOfFileToken: Token; fileName: string; text: string; - amdDependencies: AmdDependency[]; + amdDependencies: ReadonlyArray; moduleName: string; - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; /** @@ -1566,7 +1578,7 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; - sourceFiles: SourceFile[]; + sourceFiles: ReadonlyArray; } interface JsonSourceFile extends SourceFile { jsonObject?: ObjectLiteralExpression; @@ -1589,7 +1601,7 @@ declare namespace ts { readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; } class OperationCanceledException { } @@ -1602,11 +1614,11 @@ declare namespace ts { /** * Get a list of root file names that were passed to a 'createProgram' */ - getRootFileNames(): string[]; + getRootFileNames(): ReadonlyArray; /** * Get a list of files in the program */ - getSourceFiles(): SourceFile[]; + getSourceFiles(): ReadonlyArray; /** * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then * the JavaScript and declaration files will be produced for all the files in this program. @@ -1618,15 +1630,16 @@ declare namespace ts { * will be invoked when writing the JavaScript and declaration files. */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** - * Gets a type checker that can be used to semantically analyze source fils in the program. + * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; } interface CustomTransformers { /** Custom transformers to evaluate before built-in transformations. */ @@ -1669,7 +1682,7 @@ declare namespace ts { interface EmitResult { emitSkipped: boolean; /** Contains declaration emit diagnostics */ - diagnostics: Diagnostic[]; + diagnostics: ReadonlyArray; emittedFiles: string[]; } interface TypeChecker { @@ -1970,6 +1983,7 @@ declare namespace ts { IndexedAccess = 524288, NonPrimitive = 16777216, Literal = 224, + Unit = 6368, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, @@ -2172,7 +2186,7 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[]; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2372,6 +2386,11 @@ declare namespace ts { * If accessing a non-index file, this should include its name e.g. "foo/bar". */ name: string; + /** + * Name of a submodule within this package. + * May be "". + */ + subModuleName: string; /** Version of the package, e.g. "1.2.3" */ version: string; } @@ -2388,14 +2407,15 @@ declare namespace ts { interface ResolvedTypeReferenceDirective { primary: boolean; resolvedFileName?: string; + packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; failedLookupLocations: string[]; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2460,7 +2480,8 @@ declare namespace ts { SourceFile = 0, Expression = 1, IdentifierName = 2, - Unspecified = 3, + MappedTypeParameter = 3, + Unspecified = 4, } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2639,6 +2660,9 @@ declare namespace ts { /** The version of the TypeScript compiler release */ const version: string; } +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; +} declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { @@ -2834,7 +2858,60 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeIdentifier(id: string): string; - function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ + function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node: Node): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3184,8 +3261,8 @@ declare namespace ts { function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; @@ -3214,6 +3291,7 @@ declare namespace ts { function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -3231,8 +3309,13 @@ declare namespace ts { function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; @@ -3388,10 +3471,12 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: SourceFile[]): Bundle; - function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createBundle(sourceFiles: ReadonlyArray): Bundle; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[]): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3575,8 +3660,8 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; getNewLine(): string; } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -3591,7 +3676,7 @@ declare namespace ts { * @param oldProgram - Reuses an old program structure. * @returns A 'Program' object. */ - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; @@ -3700,7 +3785,7 @@ declare namespace ts { interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; - getLineStarts(): number[]; + getLineStarts(): ReadonlyArray; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; } @@ -3917,7 +4002,7 @@ declare namespace ts { * Represents a single refactoring action - for example, the "Extract Method..." refactor might * offer several actions, each corresponding to a surround class or closure to extract into. */ - type RefactorActionInfo = { + interface RefactorActionInfo { /** * The programmatic name of the refactoring action */ @@ -3928,16 +4013,16 @@ declare namespace ts { * so this description should make sense by itself if the parent is inlineable=true */ description: string; - }; + } /** * A set of edits to make in response to a refactor action, plus an optional * location where renaming should be invoked from */ - type RefactorEditInfo = { + interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename?: string; - renameLocation?: number; - }; + renameFilename: string | undefined; + renameLocation: number | undefined; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ diff --git a/lib/typescript.js b/lib/typescript.js index f1356d558c67c..4128b5d17fa8f 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -800,6 +800,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -1200,6 +1201,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1242,7 +1244,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); /*@internal*/ @@ -1349,6 +1352,15 @@ var ts; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); /* @internal */ (function (ts) { // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. @@ -1375,7 +1387,6 @@ var ts; return new MapCtr(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - /* @internal */ function createSymbolTable(symbols) { var result = createMap(); if (symbols) { @@ -2063,6 +2074,32 @@ var ts; return to; } ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ @@ -2236,11 +2273,6 @@ var ts; ts.getProperty = getProperty; /** * Gets the owned, enumerable property keys of a map-like. - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * Object.keys instead as it offers better performance. - * - * @param map A map-like. */ function getOwnKeys(map) { var keys = []; @@ -2252,6 +2284,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2426,6 +2468,9 @@ var ts; /** Does nothing. */ function noop() { } ts.noop = noop; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -2503,12 +2548,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2768,21 +2812,13 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; - /* @internal */ function pathIsRelative(path) { return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2803,7 +2839,6 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; - /* @internal */ function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2821,7 +2856,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3021,17 +3056,14 @@ var ts; return true; } ts.containsPath = containsPath; - /* @internal */ function startsWith(str, prefix) { return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; - /* @internal */ function removePrefix(str, prefix) { return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; - /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3045,7 +3077,6 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - /* @internal */ function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; @@ -3061,7 +3092,6 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /* @internal */ ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -3551,6 +3581,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3617,7 +3651,6 @@ var ts; * Return an exact match if possible, or a pattern match, or undefined. * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) */ - /* @internal */ function matchPatternOrExact(patternStrings, candidate) { var patterns = []; for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { @@ -3634,7 +3667,6 @@ var ts; return findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; - /* @internal */ function patternText(_a) { var prefix = _a.prefix, suffix = _a.suffix; return prefix + "*" + suffix; @@ -3644,14 +3676,12 @@ var ts; * Given that candidate matches pattern, returns the text matching the '*'. * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" */ - /* @internal */ function matchedText(pattern, candidate) { Debug.assert(isPatternMatch(pattern, candidate)); return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); } ts.matchedText = matchedText; /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ function findBestPatternMatch(values, getPattern, candidate) { var matchedValue = undefined; // use length of prefix as betterness criteria @@ -3673,7 +3703,6 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } - /* @internal */ function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); @@ -3719,6 +3748,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); /// var ts; @@ -4320,8 +4355,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4641,7 +4676,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4714,6 +4751,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4831,7 +4869,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4936,17 +4974,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -5037,6 +5074,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5084,7 +5122,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); /// @@ -5364,7 +5402,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline } return res; } @@ -6889,7 +6927,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -6915,15 +6952,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -6957,7 +6993,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -7116,7 +7152,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while @@ -7157,6 +7193,19 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 /* LessThan */ : bPos < aPos ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } /** * Gets flags that control emit behavior of a node. */ @@ -7191,6 +7240,7 @@ var ts; case 16 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -7304,6 +7354,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 273 /* JSDocFunctionType */: + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 282 /* JSDocTemplateTag */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8029,59 +8107,62 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 99 /* ThisKeyword */: - var parent = node.parent; - switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 176 /* BindingElement */: - return parent.initializer === node; - case 210 /* ExpressionStatement */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 219 /* ReturnStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 223 /* ThrowStatement */: - return parent.expression === node; - case 214 /* ForStatement */: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || - forInStatement.expression === node; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return node === parent.expression; - case 205 /* TemplateSpan */: - return node === parent.expression; - case 144 /* ComputedPropertyName */: - return node === parent.expression; - case 147 /* Decorator */: - case 256 /* JsxExpression */: - case 255 /* JsxSpreadAttribute */: - case 263 /* SpreadAssignment */: - return true; - case 201 /* ExpressionWithTypeArguments */: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 264 /* EnumMember */: + case 261 /* PropertyAssignment */: + case 176 /* BindingElement */: + return parent.initializer === node; + case 210 /* ExpressionStatement */: + case 211 /* IfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 219 /* ReturnStatement */: + case 220 /* WithStatement */: + case 221 /* SwitchStatement */: + case 257 /* CaseClause */: + case 223 /* ThrowStatement */: + return parent.expression === node; + case 214 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return node === parent.expression; + case 205 /* TemplateSpan */: + return node === parent.expression; + case 144 /* ComputedPropertyName */: + return node === parent.expression; + case 147 /* Decorator */: + case 256 /* JsxExpression */: + case 255 /* JsxSpreadAttribute */: + case 263 /* SpreadAssignment */: + return true; + case 201 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; } @@ -8261,14 +8342,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -8276,15 +8349,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -8324,23 +8388,17 @@ var ts; } // Pull parameter comments from declaring function as well if (node.kind === 146 /* Parameter */) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - // a binding pattern doesn't have a name, so it's not possible to match it a jsdoc parameter, which is identified by name - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { @@ -8367,38 +8425,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); - if (!tag && node.kind === 146 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278 /* JSDocClassTag */); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -8410,7 +8436,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { return true; } } @@ -8848,9 +8874,9 @@ var ts; || kind === 265 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -9119,6 +9145,7 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine }); + var escapedNullRegExp = /\\0[0-9]/g; /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -9128,9 +9155,12 @@ var ts; var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -9433,7 +9463,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -9446,7 +9476,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -9459,7 +9489,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -10127,6 +10157,45 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 193 /* PostfixUnaryExpression */: + case 192 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 194 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + case 179 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && parent.parent.kind === 210 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10526,6 +10595,63 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases + switch (hostNode.kind) { + case 208 /* VariableStatement */: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 179 /* PropertyAccessExpression */: + return expr.name; + case 180 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1 /* EndOfFileToken */: + return undefined; + case 185 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -10545,11 +10671,124 @@ var ts; return undefined; } } + else if (declaration.kind === 283 /* JSDocTypedefTag */) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + if (!tag && node.kind === 146 /* Parameter */) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -11213,8 +11452,7 @@ var ts; // Node Arrays /* @internal */ function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; // Literals @@ -11310,16 +11548,28 @@ var ts; } ts.isFunctionLike = isFunctionLike; /* @internal */ - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152 /* Constructor */: - case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* Constructor */: case 153 /* GetAccessor */: case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 150 /* MethodSignature */: case 155 /* CallSignature */: case 156 /* ConstructSignature */: case 157 /* IndexSignature */: @@ -11327,10 +11577,16 @@ var ts; case 273 /* JSDocFunctionType */: case 161 /* ConstructorType */: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; // Classes function isClassElement(node) { var kind = node.kind; @@ -11513,54 +11769,63 @@ var ts; || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 /* PropertyAccessExpression */ - || kind === 180 /* ElementAccessExpression */ - || kind === 182 /* NewExpression */ - || kind === 181 /* CallExpression */ - || kind === 249 /* JsxElement */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 183 /* TaggedTemplateExpression */ - || kind === 177 /* ArrayLiteralExpression */ - || kind === 185 /* ParenthesizedExpression */ - || kind === 178 /* ObjectLiteralExpression */ - || kind === 199 /* ClassExpression */ - || kind === 186 /* FunctionExpression */ - || kind === 71 /* Identifier */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 9 /* StringLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 196 /* TemplateExpression */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 91 /* ImportKeyword */ - || kind === 203 /* NonNullExpression */ - || kind === 204 /* MetaProperty */; - } /* @internal */ function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */ - || kind === 188 /* DeleteExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 190 /* VoidExpression */ - || kind === 191 /* AwaitExpression */ - || kind === 184 /* TypeAssertionExpression */ - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + case 182 /* NewExpression */: + case 181 /* CallExpression */: + case 249 /* JsxElement */: + case 250 /* JsxSelfClosingElement */: + case 183 /* TaggedTemplateExpression */: + case 177 /* ArrayLiteralExpression */: + case 185 /* ParenthesizedExpression */: + case 178 /* ObjectLiteralExpression */: + case 199 /* ClassExpression */: + case 186 /* FunctionExpression */: + case 71 /* Identifier */: + case 12 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 196 /* TemplateExpression */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 101 /* TrueKeyword */: + case 97 /* SuperKeyword */: + case 203 /* NonNullExpression */: + case 204 /* MetaProperty */: + case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } } /* @internal */ function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192 /* PrefixUnaryExpression */: + case 193 /* PostfixUnaryExpression */: + case 188 /* DeleteExpression */: + case 189 /* TypeOfExpression */: + case 190 /* VoidExpression */: + case 191 /* AwaitExpression */: + case 184 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { @@ -11574,22 +11839,31 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 /* ConditionalExpression */ - || kind === 197 /* YieldExpression */ - || kind === 187 /* ArrowFunction */ - || kind === 194 /* BinaryExpression */ - || kind === 198 /* SpreadElement */ - || kind === 202 /* AsExpression */ - || kind === 200 /* OmittedExpression */ - || kind === 289 /* CommaListExpression */ - || isUnaryExpressionKind(kind); - } /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isPartOfExpression` if not in transforms. + */ function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195 /* ConditionalExpression */: + case 197 /* YieldExpression */: + case 187 /* ArrowFunction */: + case 194 /* BinaryExpression */: + case 198 /* SpreadElement */: + case 202 /* AsExpression */: + case 200 /* OmittedExpression */: + case 289 /* CommaListExpression */: + case 288 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 /* TypeAssertionExpression */ @@ -11865,6 +12139,12 @@ var ts; return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); /// /// @@ -12301,9 +12581,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285 /* JSDocTypeLiteral */: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288 /* PartiallyEmittedExpression */: @@ -12599,7 +12881,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -12742,9 +13024,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } // Use this function to access the current token instead of reading the currentToken // variable. Since function results aren't narrowed in control flow analysis, this ensures // that the type checker doesn't make wrong assumptions about the type of the current @@ -12903,13 +13182,14 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -12964,7 +13244,9 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -13246,20 +13528,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -13541,12 +13823,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma @@ -13583,6 +13866,8 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); // Recording the trailing comma is deliberately done after the previous // loop, and not just if we see a list terminator. This is because the list // may have ended incorrectly, but it is still important to know if there @@ -13592,12 +13877,10 @@ var ts; // Always preserve a trailing comma by marking it on the NodeArray result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -13662,12 +13945,12 @@ var ts; var template = createNode(196 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -13779,7 +14062,7 @@ var ts; var result = createNode(273 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159 /* TypeReference */); node.typeName = parseIdentifierName(); @@ -13848,9 +14131,10 @@ var ts; return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || isStartOfType(); + token() === 57 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); @@ -13876,38 +14160,34 @@ var ts; } node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ true); + node.initializer = parseInitializer(/*inParameter*/ true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(/*inParameter*/ true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36 /* EqualsGreaterThanToken */) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56 /* ColonToken */)) { + return true; } - else if (flags & 4 /* Type */) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 /* ColonToken */ ? 36 /* EqualsGreaterThanToken */ : 56 /* ColonToken */); - if (backwardToken) { - // This is easy to get backward, especially in type contexts, so parse the type anyway - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { // FormalParameters [Yield,Await]: (modified) @@ -13928,7 +14208,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8 /* RequireCompleteParameterList */)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { @@ -14024,7 +14304,7 @@ var ts; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -14167,7 +14447,7 @@ var ts; parseExpected(94 /* NewKeyword */); } fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -14181,16 +14461,9 @@ var ts; unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } - var expression; - switch (token()) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - expression = parseLiteralLikeNode(token()); - break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - expression = parseTokenNode(); - } + var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -14224,6 +14497,7 @@ var ts; return parseJSDocNodeWithType(274 /* JSDocVariadicType */); case 51 /* ExclamationToken */: return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: @@ -14255,7 +14529,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119 /* AnyKeyword */: case 136 /* StringKeyword */: @@ -14280,13 +14554,16 @@ var ts; case 86 /* FalseKeyword */: case 134 /* ObjectKeyword */: case 39 /* AsteriskToken */: + case 55 /* QuestionToken */: + case 51 /* ExclamationToken */: + case 24 /* DotDotDotToken */: return true; case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -14353,13 +14630,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -14545,7 +14821,7 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse @@ -14560,6 +14836,13 @@ var ts; // do not try to parse initializer return undefined; } + if (inParameter && requireEqualsToken) { + // = is required when speculatively parsing arrow function parameters, + // so return a fake initializer as a signal that the equals token was missing + var result = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } // Initializer[In, Yield] : // = AssignmentExpression[?In, ?Yield] @@ -14685,8 +14968,7 @@ var ts; var parameter = createNode(146 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); @@ -14835,8 +15117,7 @@ var ts; function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 120 /* AsyncKeyword */) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -14887,7 +15168,8 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && ((token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } @@ -15447,7 +15729,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { @@ -15467,12 +15750,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254 /* JsxAttributes */); @@ -16446,7 +16728,7 @@ var ts; var node = createNode(176 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { @@ -16462,7 +16744,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingPattern() { @@ -16496,7 +16778,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -16699,7 +16981,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57 /* AtToken */)) { @@ -16708,17 +16991,9 @@ var ts; var decorator = createNode(147 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); + (list || (list = [])).push(decorator); } - return decorators; + return list && createNodeArray(list, listPos); } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. @@ -16728,7 +17003,8 @@ var ts; * In such situations, 'permitInvalidConstAsModifier' should be set to true. */ function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -16745,17 +17021,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); + (list || (list = [])).push(modifier); } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -16765,7 +17033,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -17323,11 +17590,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - // Parses out a JSDoc type expression. - /* @internal */ - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); - parseExpected(17 /* OpenBraceToken */); + if (!parseExpected(17 /* OpenBraceToken */) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); parseExpected(18 /* CloseBraceToken */); fixupParentReferences(result); @@ -17384,6 +17651,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; // Check for /** (JSDoc opening part) @@ -17507,7 +17776,7 @@ var ts; } function createJSDocComment() { var result = createNode(275 /* JSDocComment */, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -17637,21 +17906,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17 /* OpenBraceToken */) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' @@ -17743,11 +18008,11 @@ var ts; var result = createNode(281 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -17784,19 +18049,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); } if (child.kind === 281 /* JSDocTypeTag */) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -17810,7 +18074,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -17905,7 +18171,8 @@ var ts; parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name = parseJSDocIdentifierName(); skipWhitespace(); @@ -17928,9 +18195,8 @@ var ts; var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -18072,7 +18338,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -18622,9 +18888,11 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { - symbol.declarations = []; + symbol.declarations = [node]; + } + else { + symbol.declarations.push(node); } - symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } @@ -18695,17 +18963,8 @@ var ts; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; case 283 /* JSDocTypedefTag */: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (ts.isIdentifier(nameIdentifier)) { - nameFromParentNode = nameIdentifier.escapedText; - } - } - } - return nameFromParentNode; + var name_2 = ts.getNameOfJSDocTypedef(node); + return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -18993,7 +19252,7 @@ var ts; // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; @@ -19795,10 +20054,6 @@ var ts; lastContainer = next; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { // Modules, source files, and classes need specialized handling for how their // members are declared (for example, a member of a class will go into a specific @@ -19995,6 +20250,9 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & 8 /* EnumMember */) { + symbol.parent = container.symbol; + } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { @@ -20205,7 +20463,7 @@ var ts; inStrictMode = saveInStrictMode; } function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { + if (!ts.hasJSDocNodes(node)) { return; } for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -21615,31 +21873,38 @@ var ts; return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = ts.createMap(); // Key is id as string - var visitedSymbols = ts.createMap(); // Key is id as string + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol return { walkType: function (type) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitType(type); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, walkSymbol: function (symbol) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitSymbol(symbol); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, }; function visitType(type) { if (!type) { return; } - var typeIdString = type.id.toString(); - if (visitedTypes.has(typeIdString)) { + if (visitedTypes[type.id]) { return; } - visitedTypes.set(typeIdString, type); + visitedTypes[type.id] = type; // Reuse visitSymbol to visit the type's symbol, // but be sure to bail on recuring into the type if accept declines the symbol. var shouldBail = visitSymbol(type.symbol); @@ -21675,23 +21940,15 @@ var ts; visitIndexedAccessType(type); } } - function visitTypeList(types) { - if (!types) { - return; - } - for (var i = 0; i < types.length; i++) { - visitType(types[i]); - } - } function visitTypeReference(type) { visitType(type.target); - visitTypeList(type.typeArguments); + ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { visitType(getConstraintFromTypeParameter(type)); } function visitUnionOrIntersectionType(type) { - visitTypeList(type.types); + ts.forEach(type.types, visitType); } function visitIndexType(type) { visitType(type.type); @@ -21711,7 +21968,7 @@ var ts; if (signature.typePredicate) { visitType(signature.typePredicate.type); } - visitTypeList(signature.typeParameters); + ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; visitSymbol(parameter); @@ -21721,8 +21978,8 @@ var ts; } function visitInterfaceType(interfaceT) { visitObjectType(interfaceT); - visitTypeList(interfaceT.typeParameters); - visitTypeList(getBaseTypes(interfaceT)); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); visitType(interfaceT.thisType); } function visitObjectType(type) { @@ -21749,11 +22006,11 @@ var ts; if (!symbol) { return; } - var symbolIdString = ts.getSymbolId(symbol).toString(); - if (visitedSymbols.has(symbolIdString)) { + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { return; } - visitedSymbols.set(symbolIdString, symbol); + visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { return true; } @@ -21813,7 +22070,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -21928,12 +22185,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -22333,7 +22590,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -22515,32 +22772,41 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -22588,9 +22854,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); @@ -22801,6 +23078,7 @@ var ts; var enumCount = 0; var symbolInstantiationDepth = 0; var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -22961,12 +23239,13 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + isArrayLikeType: isArrayLikeType, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; @@ -23055,7 +23334,8 @@ var ts; var deferredUnusedIdentifierNodes; var flowLoopStart = 0; var flowLoopCount = 0; - var visitedFlowCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); var resolutionTargets = []; @@ -23070,8 +23350,8 @@ var ts; var flowLoopNodes = []; var flowLoopKeys = []; var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; @@ -23205,6 +23485,7 @@ var ts; })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; function getJsxNamespace() { @@ -23288,7 +23569,7 @@ var ts; } function cloneSymbol(symbol) { var result = createSymbol(symbol.flags, symbol.escapedName); - result.declarations = symbol.declarations.slice(0); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -23387,6 +23668,7 @@ var ts; mergeSymbol(mainModule, moduleAugmentation.symbol); } else { + // moduleName will be a StringLiteral since this is not `declare global`. error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); } } @@ -23555,13 +23837,17 @@ var ts; }); } } - // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and - // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with - // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -23780,10 +24066,16 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 265 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports") { + return lastLocation.symbol; + } + } result = lookup(globals, name, meaning); } if (!result) { @@ -23917,7 +24209,7 @@ var ts; } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -23941,7 +24233,7 @@ var ts; error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -23951,14 +24243,14 @@ var ts; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -23991,11 +24283,17 @@ var ts; return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); + case 239 /* ImportClause */: + return node.parent; + case 240 /* NamespaceImport */: + return node.parent.parent; + case 242 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; } } function getDeclarationOfAliasSymbol(symbol) { @@ -24248,7 +24546,7 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, /*isUse*/ true); if (!symbol) { return undefined; } @@ -24295,7 +24593,7 @@ var ts; undefined; } else { - ts.Debug.fail("Unknown entity name kind."); + ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -24346,13 +24644,13 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -24465,10 +24763,9 @@ var ts; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { return; } - visitedSymbols.push(symbol); var symbols = ts.cloneMap(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports.get("__export" /* ExportStar */); @@ -24616,65 +24913,61 @@ var ts; return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { + var visitedSymbolTables = []; + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - visitedSymbolTables.push(symbols); var result = trySymbolTable(symbols); visitedSymbolTables.pop(); return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolFromSymbolTable or alias resolution matches the symbol, - // check the symbol can be qualified, it is only then this symbol is accessible - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 /* Alias */ - && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || // We can use any type of alias to get the name - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + function isUMDExportSymbol(symbol) { + return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */) + && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } - }); - } - } - if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { @@ -24813,14 +25106,7 @@ var ts; // since we will do the emitting later in trackSymbol. if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } @@ -24848,7 +25134,7 @@ var ts; meaning = 793064 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, @@ -24882,7 +25168,7 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { @@ -25174,14 +25460,14 @@ var ts; var i = 0; var qualifiedName = void 0; if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -25457,29 +25743,6 @@ var ts; } } } - function getNameOfSymbol(symbol, context) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } - } - return ts.unescapeLeadingUnderscores(symbol.escapedName); - } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { return ts.usingSingleLineStringWriter(function (writer) { @@ -25537,9 +25800,9 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol) { + function getNameOfSymbol(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -25549,6 +25812,9 @@ var ts; if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } + if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } switch (declaration.kind) { case 199 /* ClassExpression */: return "(Anonymous class)"; @@ -25557,6 +25823,12 @@ var ts; return "(Anonymous function)"; } } + if (symbol.syntheticLiteralTypeOrigin) { + var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { + return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; + } + } return ts.unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder() { @@ -25794,14 +26066,14 @@ var ts; var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { - var length_3 = outerTypeParameters.length; - while (i < length_3) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -26349,7 +26621,7 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node, /*isUse*/ false); } else if (node.parent.kind === 246 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); @@ -26363,14 +26635,12 @@ var ts; ts.forEach(declarations, function (declaration) { getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } + ts.pushIfUnique(result, resultNode); if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -26393,8 +26663,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_4 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_4; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -27104,38 +27374,50 @@ var ts; for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } + typeParameters = ts.appendIfUnique(typeParameters, tp); } return typeParameters; } - // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function - // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and - // returns the same array. - function appendOuterTypeParameters(typeParameters, node) { + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; if (!node) { - return typeParameters; + return undefined; } - if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || - node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } + switch (node.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 273 /* JSDocFunctionType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 231 /* TypeAliasDeclaration */: + case 282 /* JSDocTemplateTag */: + case 172 /* MappedType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 172 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var thisType = includeThisTypes && + (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || node.kind === 230 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); + return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. @@ -27189,7 +27471,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -27280,7 +27562,7 @@ var ts; var valueDecl = type.symbol.valueDeclaration; if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { + if (augTag && augTag.typeExpression && augTag.typeExpression.type) { baseType = getTypeFromTypeNode(augTag.typeExpression.type); } } @@ -27410,7 +27692,9 @@ var ts; var declaration = ts.find(symbol.declarations, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); - var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); + var typeNode = declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -27761,7 +28045,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -27798,9 +28082,7 @@ var ts; if (!match) { return undefined; } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } + result = ts.appendIfUnique(result, match); } return result; } @@ -28009,7 +28291,14 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { + function addMemberForKeyType(t, propertySymbolOrIndex) { + var propertySymbol; + // forEachType delegates to forEach, which calls with a numeric second argument + // the type system currently doesn't catch this incompatibility, so we annotate + // the function ourselves to indicate the runtime behavior and deal with it here + if (typeof propertySymbolOrIndex === "object") { + propertySymbol = propertySymbolOrIndex; + } // Create a mapper from T to the current iteration type constituent. Then, if the // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. @@ -28029,6 +28318,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } + prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } else if (t.flags & 2 /* String */) { @@ -28151,26 +28441,22 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getAllPossiblePropertiesOfType(type) { - if (type.flags & 65536 /* Union */) { - var props = ts.createSymbolTable(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var memberType = _a[_i]; - if (memberType.flags & 8190 /* Primitive */) { - continue; - } - for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { - var escapedName = _c[_b].escapedName; - if (!props.has(escapedName)) { - props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); - } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 65536 /* Union */)) { + return getPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var memberType = types_2[_i]; + for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); } } - return ts.arrayFrom(props.values()); - } - else { - return getPropertiesOfType(type); } + return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : @@ -28237,8 +28523,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type_2 = types_2[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type_2 = types_3[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -28316,20 +28602,15 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var current = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var current = types_4[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } + props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | @@ -28479,12 +28760,7 @@ var ts; var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - if (!result) { - result = []; - } - result.push(tp); - } + result = ts.appendIfUnique(result, tp); }); return result; } @@ -28520,7 +28796,7 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); // merged symbol is module declaration symbol combined with all augmentations return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } @@ -28583,11 +28859,10 @@ var ts; * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { if (!typeArguments) { typeArguments = []; @@ -28626,7 +28901,7 @@ var ts; var paramSymbol = param.symbol; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -28822,8 +29097,8 @@ var ts; } return anyType; } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -28836,12 +29111,27 @@ var ts; return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); - } - return signature.erasedSignatureCache; + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } function getOrCreateTypeFromSignature(signature) { // There are two ways to declare a construct signature, one is by declaring a class constructor @@ -28911,12 +29201,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_5 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_5) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_5 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -28937,8 +29227,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -28977,7 +29267,8 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var isJavascript = ts.isInJavaScriptFile(node); + if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); @@ -28986,7 +29277,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -29002,7 +29293,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); } return instantiation; } @@ -29214,7 +29505,8 @@ var ts; return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -29374,6 +29666,22 @@ var ts; function containsType(types, type) { return binarySearchTypes(types, type) >= 0; } + // Return true if the given intersection type contains (a) more than one unit type or (b) an object + // type and a nullable type (null or undefined). + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6368 /* Unit */ && combined & 6368 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 6144 /* Nullable */ && combined & (32768 /* Object */ | 16777216 /* NonPrimitive */)) { + return true; + } + } + return false; + } function addTypeToUnion(typeSet, type) { var flags = type.flags; if (flags & 65536 /* Union */) { @@ -29390,7 +29698,11 @@ var ts; if (!(flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 /* Never */)) { + else if (!(flags & 8192 /* Never */ || flags & 131072 /* Intersection */ && isEmptyIntersectionType(type))) { + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. if (flags & 2 /* String */) typeSet.containsString = true; if (flags & 4 /* Number */) @@ -29410,14 +29722,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29425,8 +29737,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -29519,6 +29831,12 @@ var ts; type = createType(65536 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } @@ -29560,8 +29878,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; addTypeToIntersection(typeSet, type); } } @@ -29608,7 +29926,7 @@ var ts; type = createType(131072 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; - type.aliasSymbol = aliasSymbol; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. type.aliasTypeArguments = aliasTypeArguments; } return type; @@ -29720,21 +30038,6 @@ var ts; } return anyType; } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - if (accessNode) { - // Check if the index type is assignable to 'keyof T' for the object type. - if (!isTypeAssignableTo(indexType, getIndexType(type))) { - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); - return unknownType; - } - if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { - error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - } - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } function isGenericObjectType(type) { return type.flags & 540672 /* TypeVariable */ ? true : getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : @@ -29757,12 +30060,14 @@ var ts; } return false; } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // undefined if no transformation is possible. function getTransformedIndexedAccessType(type) { var objectType = type.objectType; + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; @@ -29780,19 +30085,22 @@ var ts; getIntersectionType(stringIndexTypes) ]); } - return undefined; - } - function getIndexedAccessType(objectType, indexType, accessNode) { - // If the object type is a mapped type { [P in K]: E }, where K is generic, we instantiate E using a mapper + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - // Otherwise, if the index type is generic, or if the object type is generic and doesn't originate in an - // expression, we are performing a higher-order index access where we cannot meaningfully access the properties - // of the object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates - // in an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + return undefined; + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { @@ -29807,8 +30115,10 @@ var ts; return type; } // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -29892,7 +30202,10 @@ var ts; return mapType(right, function (t) { return getSpreadType(left, t); }); } if (right.flags & 16777216 /* NonPrimitive */) { - return emptyObjectType; + return nonPrimitiveType; + } + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 262178 /* StringLike */ | 272 /* EnumLike */)) { + return left; } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); @@ -30120,10 +30433,6 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } function makeUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -30142,11 +30451,9 @@ var ts; } function createTypeMapper(sources, targets) { ts.Debug.assert(targets === undefined || sources.length === targets.length); - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -30156,9 +30463,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; + return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -30168,18 +30473,11 @@ var ts; createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } - function identityMapper(type) { - return type; - } function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; + return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; + return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { var result = createType(16384 /* TypeParameter */); @@ -30246,15 +30544,57 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } + if (symbol.isRestParameter) { + result.isRestParameter = symbol.isRestParameter; + } return result; } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); - result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; - result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are actually referenced somewhere in the literal. + var declaration_1 = symbol.declarations[0]; + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + outerTypeParameters; + links.typeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function isTypeParameterReferencedWithin(tp, node) { + return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); + function checkThis(node) { + return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + } + function checkIdentifier(node) { + return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + } } function instantiateMappedType(type, mapper) { // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some @@ -30270,161 +30610,62 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); } return t; }); } } } - return instantiateMappedObjectType(type, mapper); + return instantiateAnonymousType(type, mapper); } function isMappableType(type) { return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + } + result.target = type; + result.mapper = mapper; result.aliasSymbol = type.aliasSymbol; result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - // Starting with the parent of the symbol's declaration, check if the mapper maps any of - // the type parameters introduced by enclosing declarations. We just pick the first - // declaration since multiple declarations will all have the same parent anyway. - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { - return "quit"; - } - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var d = typeParameters_1[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172 /* MappedType */: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 273 /* JSDocFunctionType */: - var func = node; - for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { - var p = _b[_a]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; - } - return false; - } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - // If we are instantiating a type that has a top-level type alias, obtain the instantiation through - // the type alias instead in order to share instantiations for the same type arguments. This can - // dramatically reduce the number of structurally identical types we generate. Note that we can only - // perform this optimization for top-level type aliases. Consider: - // - // function f1(x: T) { - // type Foo = { x: X, t: T }; - // let obj: Foo = { x: x }; - // return obj; - // } - // function f2(x: U) { return f1(x); } - // let z = f2(42); - // - // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo - // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's - // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been - // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (type.objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } - return type; } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. We skip instantiation - // if none of the type parameters that are in scope in the type's declaration are mapped by - // the given mapper, however we can only do that analysis if the type isn't itself an - // instantiation. - return type.symbol && - type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 32 /* Mapped */) { - return instantiateCached(type, mapper, instantiateMappedType); + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); } - if (type.objectFlags & 4 /* Reference */) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } return type; } function instantiateIndexInfo(info, mapper) { @@ -30437,6 +30678,7 @@ var ts; switch (node.kind) { case 186 /* FunctionExpression */: case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); case 178 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); @@ -30450,9 +30692,6 @@ var ts; (isContextSensitive(node.left) || isContextSensitive(node.right)); case 261 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return isContextSensitiveFunctionLikeDeclaration(node); case 185 /* ParenthesizedExpression */: return isContextSensitive(node.expression); case 254 /* JsxAttributes */: @@ -30569,7 +30808,8 @@ var ts; if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0 /* False */; } - if (source.typeParameters) { + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var result = -1 /* True */; @@ -30842,7 +31082,14 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var expandingFlags = 0; + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var expandingFlags = 0 /* None */; var overflow = false; var isIntersectionConstituent = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); @@ -31060,10 +31307,21 @@ var ts; else { // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { - errorNode = prop.valueDeclaration; + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + if (ts.isIdentifier(propDeclaration.name)) { + suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } return { value: true }; @@ -31229,11 +31487,11 @@ var ts; targetStack[depth] = target; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -31287,7 +31545,7 @@ var ts; else if (target.flags & 524288 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and // A is the apparent type of S. - var constraint = getConstraintOfType(target); + var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { errorInfo = saveErrorInfo; @@ -31326,7 +31584,7 @@ var ts; else if (source.flags & 524288 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and // A is the apparent type of S. - var constraint = getConstraintOfType(source); + var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { errorInfo = saveErrorInfo; @@ -31414,22 +31672,21 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + } + return 0 /* False */; + } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 16777216 /* Optional */) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0 /* False */; - } - } - else if (!(targetProp.flags & 4194304 /* Prototype */)) { + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { @@ -31737,13 +31994,14 @@ var ts; return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" * where A.id=111 and number.id=12 */ - function getTypeReferenceId(type, typeParameters) { + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } var result = "" + type.target.id; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; @@ -31755,6 +32013,9 @@ var ts; } result += "=" + index; } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } else { result += "-" + t.id; } @@ -31958,8 +32219,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -32000,7 +32261,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return !!(type.flags & 6368 /* Unit */); } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : @@ -32032,8 +32293,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -32276,7 +32537,6 @@ var ts; function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; - context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -32317,7 +32577,7 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 /* TypeVariable */ || + return !!(type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || @@ -32375,18 +32635,18 @@ var ts; return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); } } - function isPossiblyAssignableTo(source, target) { + function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (!(targetProp.flags & (16777216 /* Optional */ | 4194304 /* Prototype */))) { - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return false; + return targetProp; } } } - return true; + return undefined; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } @@ -32483,6 +32743,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 262144 /* Index */ && target.flags & 262144 /* Index */) { + inferFromTypes(source.type, target.type); + } + else if (source.flags & 524288 /* IndexedAccess */ && target.flags & 524288 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (target.flags & 196608 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -32508,7 +32775,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 196608 /* UnionOrIntersection */) { + else if (source.flags & 65536 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -32518,7 +32785,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 32768 /* Object */) { + if (source.flags & (32768 /* Object */ | 131072 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -32557,6 +32824,12 @@ var ts; return undefined; } function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } if (getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); if (constraintType.flags & 262144 /* Index */) { @@ -32586,7 +32859,7 @@ var ts; } // Infer from the members of source and target only if the two types are possibly related. We check // in both directions because we may be inferring for a co-variant or a contra-variant position. - if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + if (!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) || !getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -32597,7 +32870,7 @@ var ts; var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -32643,8 +32916,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -32734,7 +33007,8 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -32915,8 +33189,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -33183,8 +33457,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -33264,8 +33538,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -33319,15 +33593,25 @@ var ts; } return false; } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return unknownType; + } if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } - var visitedFlowStart = visitedFlowCount; + var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; + sharedFlowCount = sharedFlowStart; // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without @@ -33338,60 +33622,70 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { + if (flowDepth === 2500) { + // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return unknownType; + } + flowDepth++; while (true) { - if (flow.flags & 1024 /* Shared */) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; } } } var type = void 0; - if (flow.flags & 4096 /* AfterFinally */) { + if (flags & 4096 /* AfterFinally */) { // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flow.flags & 2048 /* PreFinally */) { + else if (flags & 2048 /* PreFinally */) { // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel // so here just redirect to antecedent flow = flow.antecedent; continue; } - else if (flow.flags & 16 /* Assignment */) { + else if (flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 96 /* Condition */) { + else if (flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } - else if (flow.flags & 128 /* SwitchClause */) { + else if (flags & 128 /* SwitchClause */) { type = getTypeAtSwitchClause(flow); } - else if (flow.flags & 12 /* Label */) { + else if (flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flow.flags & 4 /* BranchLabel */ ? + type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flow.flags & 256 /* ArrayMutation */) { + else if (flags & 256 /* ArrayMutation */) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 2 /* Start */) { + else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { @@ -33406,12 +33700,13 @@ var ts; // simply return the non-auto declared type to reduce follow-on errors. type = convertAutoToAny(declaredType); } - if (flow.flags & 1024 /* Shared */) { + if (flags & 1024 /* Shared */) { // Record visited node and the associated type in the cache. - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; } + flowDepth--; return type; } } @@ -33447,30 +33742,32 @@ var ts; return undefined; } function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { - var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 181 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 181 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + return flowType; } - return flowType; } return undefined; } @@ -33530,9 +33827,7 @@ var ts; if (type === declaredType && declaredType === initialType) { return type; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); // If an antecedent type is not a subset of the declared type, we need to perform // subtype reduction. This happens when a "foreign" type is injected into the control // flow using the instanceof operator or a user defined type predicate. @@ -33598,9 +33893,7 @@ var ts; if (cached_1) { return cached_1; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); // If an antecedent type is not a subset of the declared type, we need to perform // subtype reduction. This happens when a "foreign" type is injected into the control // flow using the instanceof operator or a user defined type predicate. @@ -34571,7 +34864,8 @@ var ts; } } } - if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var inJs = ts.isInJavaScriptFile(func); + if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { // We have an object literal method. Check if the containing object literal has a contextual type @@ -34598,10 +34892,19 @@ var ts; } // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. - if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { - var target = func.parent.left; + var parent = func.parent; + if (parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = parent.left; if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { - return checkExpressionCached(target.expression); + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); } } } @@ -34776,7 +35079,7 @@ var ts; // expression has no contextual type, the right operand is contextually typed by the type of the left operand. var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left, /*cache*/ true); } return type; } @@ -34834,16 +35137,10 @@ var ts; // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated // type of T. - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1 /* Number */) - || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); - } - return undefined; + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node) { @@ -34948,15 +35245,21 @@ var ts; return getContextualTypeForObjectLiteralElement(parent); case 263 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: - return getContextualTypeForElementExpression(node); + case 177 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } case 195 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); case 205 /* TemplateSpan */: ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: - return getContextualType(parent); + case 185 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } case 256 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 253 /* JsxAttribute */: @@ -35028,8 +35331,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -35072,8 +35375,9 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elements.length; index++) { + var e = elements[index]; if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { // Given the following situation: // var c: {}; @@ -35095,7 +35399,8 @@ var ts; } } else { - var type = checkExpressionForMutableLocation(e, checkMode); + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; @@ -35108,9 +35413,9 @@ var ts; type.pattern = node; return type; } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; + var contextualType_1 = getApparentTypeOfContextualType(node); + if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { + var pattern = contextualType_1.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { @@ -35118,7 +35423,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType_1.typeArguments[i]); } else { if (patternElement.kind !== 200 /* OmittedExpression */) { @@ -35230,6 +35535,7 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = memberDecl.symbol; + var literalName = void 0; if (memberDecl.kind === 261 /* PropertyAssignment */ || memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { @@ -35239,6 +35545,12 @@ var ts; } var type = void 0; if (memberDecl.kind === 261 /* PropertyAssignment */) { + if (memberDecl.name.kind === 144 /* ComputedPropertyName */) { + var t = checkComputedPropertyName(memberDecl.name); + if (t.flags & 224 /* Literal */) { + literalName = ts.escapeLeadingUnderscores("" + t.value); + } + } type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === 151 /* MethodDeclaration */) { @@ -35253,7 +35565,7 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, member.escapedName); + var prop = createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. @@ -35262,7 +35574,7 @@ var ts; if (isOptional) { prop.flags |= 16777216 /* Optional */; } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } @@ -35316,7 +35628,7 @@ var ts; ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -35377,7 +35689,8 @@ var ts; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || + return !!(type.flags & (1 /* Any */ | 16777216 /* NonPrimitive */) || + getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || type.flags & 32768 /* Object */ && !isGenericMappedType(type) || type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } @@ -35622,8 +35935,9 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + var isJavascript = ts.isInJavaScriptFile(node); + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); @@ -36016,7 +36330,7 @@ var ts; // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -36264,19 +36578,8 @@ var ts; } return unknownType; } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - } - markPropertyAsReferenced(prop); + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -36298,6 +36601,61 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + else if (valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 149 /* PropertyDeclaration */: + return true; + case 261 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isPartOfExpression(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + ts.Debug.assert(x.length === 1); + return x[0]; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { @@ -36310,8 +36668,8 @@ var ts; } } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + if (suggestion !== undefined) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -36323,7 +36681,7 @@ var ts; return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ false, function (symbols, name, meaning) { var symbol = getSymbol(symbols, name, meaning); if (symbol) { // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -36402,11 +36760,12 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) + && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36415,15 +36774,6 @@ var ts; } } } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -36648,7 +36998,6 @@ var ts; var argCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments - var isDecorator; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -36678,7 +37027,6 @@ var ts; } } else if (node.kind === 147 /* Decorator */) { - isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } @@ -36738,7 +37086,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { // Clear out all the inference results from the last time inferTypeArguments was called on this context @@ -36756,7 +37104,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (ts.isExpression(node)) { + if (node.kind !== 147 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -36772,7 +37120,7 @@ var ts; // Above, the type of the 'value' parameter is inferred to be 'A'. var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. @@ -37415,8 +37763,9 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { candidateForTypeArgumentError = originalCandidate; break; @@ -37425,7 +37774,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -37559,15 +37908,6 @@ var ts; // Another error has already been reported return resolveErrorCall(node); } - // If the expression is a class of abstract type, then it cannot be instantiated. - // Note, only class declarations can be declared abstract. - // In the case of a merged class-module or class-interface declaration, - // only the class declaration node will have the Abstract flag set. - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } // TS 1.0 spec: 4.11 // If expressionType is of type Any, Args can be any argument // list and the result of the operation is of type Any. @@ -37586,6 +37926,15 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } // If expressionType's apparent type is an object type with no construct signatures but @@ -37732,8 +38081,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -37759,7 +38108,7 @@ var ts; // This code-path is called by language service return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -37791,18 +38140,32 @@ var ts; * file. */ function isJavaScriptConstructor(node) { - if (ts.isInJavaScriptFile(node)) { + if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; return symbol && symbol.members !== undefined; } return false; } + function getJavaScriptClassType(symbol) { + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + } + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + return getInferredClassType(symbol); + } + if (symbol.flags & 3 /* Variable */) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + return getInferredClassType(valueType.symbol); + } + } + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -37842,13 +38205,11 @@ var ts; var funcSymbol = node.expression.kind === 71 /* Identifier */ ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.flags & 16 /* Function */ && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { - return getInferredClassType(funcSymbol); + var type = funcSymbol && getJavaScriptClassType(funcSymbol); + if (type) { + return type; } - else if (noImplicitAny) { + if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -37914,7 +38275,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -38022,8 +38383,9 @@ var ts; } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.lastOrUndefined(signature.parameters); - if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } @@ -38169,9 +38531,7 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } }); return aggregatedTypes; @@ -38219,9 +38579,7 @@ var ts; if (type.flags & 8192 /* Never */) { hasReturnOfTypeNever = true; } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } else { hasReturnWithNoExpression = true; @@ -38232,9 +38590,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } + ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } @@ -38539,8 +38895,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -39097,20 +39453,6 @@ var ts; var type2 = checkExpression(node.whenFalse, checkMode); return getBestChoiceType(type1, type2); } - function checkLiteralExpression(node) { - switch (node.kind) { - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(node); - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: - return trueType; - case 86 /* FalseKeyword */: - return falseType; - } - } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with // the type of each expression, as any value may be coerced into a string. @@ -39173,9 +39515,13 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode) { + function checkExpressionForMutableLocation(node, checkMode, contextualType) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); + return shouldWiden ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -39279,13 +39625,9 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281 /* JSDocTypeTag */; }); }); - if (typecasts && typecasts.length) { - // We should have already issued an error if there were multiple type jsdocs - var cast_1 = typecasts[0]; - return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); - } + var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } @@ -39301,10 +39643,14 @@ var ts; return nullWideningType; case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: + return trueType; case 86 /* FalseKeyword */: - return checkLiteralExpression(node); + return falseType; case 196 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: @@ -39920,7 +40266,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, ts.isInJavaScriptFile(typeArgumentNodes[i])); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -39994,6 +40340,10 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } return type; } // Check if we're indexing with a numeric type and if either object or index types @@ -40296,6 +40646,8 @@ var ts; switch (d.kind) { case 230 /* InterfaceDeclaration */: case 231 /* TypeAliasDeclaration */: + // A jsdoc typedef is, by definition, a type alias + case 283 /* JSDocTypedefTag */: return 2 /* ExportType */; case 233 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -40304,7 +40656,10 @@ var ts; case 229 /* ClassDeclaration */: case 232 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; + // The below options all declare an Alias, which is allowed to merge with other values within the importing module case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 239 /* ImportClause */: var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); @@ -40613,8 +40968,11 @@ var ts; markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } function markEntityNameOrEntityExpressionAsReference(typeName) { - var rootName = typeName && getFirstIdentifier(typeName); - var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ && symbolIsValue(rootSymbol) @@ -40738,22 +41096,13 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDoc(node) { - if (!ts.isInJavaScriptFile(node)) { - return; - } - ts.forEach(node.jsDoc, checkSourceElement); - } - function checkJSDocComment(node) { - if (node.tags) { - for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - checkSourceElement(tag); - } + function checkJSDocTypedefTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } function checkFunctionOrMethodDeclaration(node) { - checkJSDoc(node); checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); @@ -40879,11 +41228,11 @@ var ts; !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); } } }); @@ -40896,15 +41245,17 @@ var ts; } return false; } - function errorUnusedLocal(node, name) { + function errorUnusedLocal(declaration, name) { + var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration.parent.parent)) { + var declaration_2 = ts.getRootDeclaration(node.parent); + if ((declaration_2.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 145 /* TypeParameter */) { return; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } function parameterNameStartsWithUnderscore(parameterName) { @@ -40920,14 +41271,14 @@ var ts; var member = _a[_i]; if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -40947,8 +41298,8 @@ var ts; } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -40961,7 +41312,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); } } } @@ -40973,7 +41324,14 @@ var ts; if (node.kind === 207 /* Block */) { checkGrammarStatementInAmbientContext(node); } - ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } if (node.locals) { registerForUnusedIdentifiersCheck(node); } @@ -41143,7 +41501,7 @@ var ts; if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { @@ -41191,7 +41549,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -41268,7 +41626,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -42955,9 +43313,9 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above - grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } } @@ -42988,7 +43346,7 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); } } @@ -43007,7 +43365,7 @@ var ts; var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); } @@ -43042,10 +43400,13 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); + if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { // system modules does not support export assignment @@ -43079,7 +43440,7 @@ var ts; if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { return; } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { // it is legal to merge type alias with other values // so count should be either 1 (just type alias) or 2 (type alias + merged value) @@ -43096,15 +43457,25 @@ var ts; }); links.exportsChecked = true; } - function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || - !!declaration.body; - } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var tags = _a[_i].tags; + ts.forEach(tags, checkSourceElement); + } + } var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -43158,8 +43529,8 @@ var ts; case 168 /* ParenthesizedType */: case 170 /* TypeOperator */: return checkSourceElement(node.type); - case 275 /* JSDocComment */: - return checkJSDocComment(node); + case 283 /* JSDocTypedefTag */: + return checkJSDocTypedefTag(node); case 279 /* JSDocParameterTag */: return checkSourceElement(node.typeExpression); case 273 /* JSDocFunctionType */: @@ -43304,6 +43675,7 @@ var ts; ts.clear(potentialNewTargetCollisions); deferredNodes = []; deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalModule(node)) { @@ -43674,12 +44046,14 @@ var ts; return sig.thisParameter; } } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } // falls through - case 97 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; case 169 /* ThisType */: - return getTypeFromTypeNode(node).symbol; + return getTypeFromThisTypeNode(node).symbol; + case 97 /* SuperKeyword */: + return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; @@ -43699,13 +44073,17 @@ var ts; // falls through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - return getPropertyOfType(objectType, node.text); - } - break; + var objectType = ts.isElementAccessExpression(node.parent) + ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined + : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) + ? getTypeFromTypeNode(node.parent.parent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 79 /* DefaultKeyword */: + return getSymbolOfNode(node.parent); + default: + return undefined; } - return undefined; } function getShorthandAssignmentValueSymbol(location) { // The function returns a value symbol of an identifier in the short-hand property assignment. @@ -43853,9 +44231,9 @@ var ts; function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { var symbols_4 = []; - var name_2 = symbol.escapedName; + var name_3 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_2); + var symbol = getPropertyOfType(t, name_3); if (symbol) { symbols_4.push(symbol); } @@ -43976,7 +44354,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -44155,6 +44533,15 @@ var ts; return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + // ensure both `typeName` and `location` are parse tree nodes. + typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. @@ -44244,7 +44631,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -44547,7 +44934,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -44569,12 +44956,6 @@ var ts; case 113 /* ProtectedKeyword */: case 112 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113 /* ProtectedKeyword */) { - lastProtected = modifier; - } - else if (modifier.kind === 112 /* PrivateKeyword */) { - lastPrivate = modifier; - } if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } @@ -45089,7 +45470,7 @@ var ts; currentKind = SetAccessor; } else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -45372,7 +45753,7 @@ var ts; } } } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } @@ -45393,8 +45774,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; if (!ts.isOmittedExpression(element)) { return checkESModuleMarker(element.name); } @@ -45409,8 +45790,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -45908,7 +46289,7 @@ var ts; || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node) + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } ts.updateParameter = updateParameter; @@ -46531,13 +46912,26 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanTokenOrBody, bodyOrUndefined) { + var equalsGreaterThanToken; + var body; + if (bodyOrUndefined === undefined) { + equalsGreaterThanToken = node.equalsGreaterThanToken; + body = ts.cast(equalsGreaterThanTokenOrBody, ts.isConciseBody); + } + else { + equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { + return n.kind === 36 /* EqualsGreaterThanToken */; + }); + body = bodyOrUndefined; + } return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node) + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } ts.updateArrowFunction = updateArrowFunction; @@ -46642,11 +47036,23 @@ var ts; return node; } ts.createConditional = createConditional; - function updateConditional(node, condition, whenTrue, whenFalse) { + function updateConditional(node, condition) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (args.length === 2) { + var whenTrue_1 = args[0], whenFalse_1 = args[1]; + return updateConditional(node, condition, node.questionToken, whenTrue_1, node.colonToken, whenFalse_1); + } + ts.Debug.assert(args.length === 4); + var questionToken = args[0], whenTrue = args[1], colonToken = args[2], whenFalse = args[3]; return node.condition !== condition + || node.questionToken !== questionToken || node.whenTrue !== whenTrue + || node.colonToken !== colonToken || node.whenFalse !== whenFalse - ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node) + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } ts.updateConditional = updateConditional; @@ -46664,6 +47070,30 @@ var ts; : node; } ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(14 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(15 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(16 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { var node = createSynthesizedNode(197 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; @@ -47795,6 +48225,17 @@ var ts; /*argumentsArray*/ paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { return createBinary(left, 26 /* CommaToken */, right); } @@ -48044,9 +48485,7 @@ var ts; var emitNode = getOrCreateEmitNode(node); for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { var helper = helpers_1[_i]; - if (!ts.contains(emitNode.helpers, helper)) { - emitNode.helpers = ts.append(emitNode.helpers, helper); - } + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); } } return node; @@ -48088,9 +48527,7 @@ var ts; var helper = sourceEmitHelpers[i]; if (predicate(helper)) { helpersRemoved++; - if (!ts.contains(targetEmitNode.helpers, helper)) { - targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); - } + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); } else if (helpersRemoved > 0) { sourceEmitHelpers[i - helpersRemoved] = helper; @@ -49055,11 +49492,9 @@ var ts; return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } - else { - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { - return ts.setTextRange(ts.createParen(expression), expression); - } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); } return expression; } @@ -49195,9 +49630,31 @@ var ts; case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 185 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } - if (outerExpression && isOuterExpression(outerExpression, kinds)) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; @@ -49223,7 +49680,8 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var create = hasExportStarsToExportValues && moduleKind !== ts.ModuleKind.System - && moduleKind !== ts.ModuleKind.ES2015; + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; if (!create) { var helpers = ts.getEmitHelpers(node); if (helpers) { @@ -49793,7 +50251,7 @@ var ts; case 186 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187 /* ArrowFunction */: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 188 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189 /* TypeOfExpression */: @@ -49809,7 +50267,7 @@ var ts; case 194 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 197 /* YieldExpression */: @@ -50649,7 +51107,7 @@ var ts; else { // export class x { } var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); exportedNames = ts.append(exportedNames, name); @@ -51047,7 +51505,7 @@ var ts; */ function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -51316,6 +51774,23 @@ var ts; * @param node The node to visit. */ function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 243 /* ExportAssignment */: + case 244 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + return node; + } switch (node.kind) { case 238 /* ImportDeclaration */: return visitImportDeclaration(node); @@ -51326,7 +51801,7 @@ var ts; case 244 /* ExportDeclaration */: return visitExportDeclaration(node); default: - return visitorWorker(node); + ts.Debug.fail("Unhandled ellided statement"); } } /** @@ -51567,7 +52042,7 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && - !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -51667,10 +52142,12 @@ var ts; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), - /*type*/ undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + /*type*/ undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -52773,7 +53250,7 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8 /* Synthesized */; name.original = undefined; - name.parent = currentScope; + name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. if (useFallback) { return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } @@ -53028,7 +53505,7 @@ var ts; function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } /** @@ -53278,6 +53755,7 @@ var ts; return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } /** @@ -53983,8 +54461,6 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - // These variables contain state that changes as we descend into the tree. - var currentSourceFile; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. * They are persisted between each SourceFile transformation and should not be reset. @@ -54006,10 +54482,8 @@ var ts; if (node.isDeclarationFile) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -54104,7 +54578,7 @@ var ts; function visitArrowFunction(node) { return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -54435,8 +54909,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { - var e = elements_4[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; if (e.kind === 263 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -54454,7 +54928,7 @@ var ts; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } else { - chunkObject.push(e); + chunkObject.push(ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } } } @@ -54693,7 +55167,7 @@ var ts; enclosingFunctionFlags = ts.getFunctionFlags(node); var updated = ts.updateArrowFunction(node, node.modifiers, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, transformFunctionBody(node)); + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } @@ -55689,58 +56163,12 @@ var ts; && node.kind === 219 /* ReturnStatement */ && !node.expression; } - function isClassLikeVariableStatement(node) { - if (!ts.isVariableStatement(node)) - return false; - var variable = ts.singleOrUndefined(node.declarationList.declarations); - return variable - && variable.initializer - && ts.isIdentifier(variable.name) - && (ts.isClassLike(variable.initializer) - || (ts.isAssignmentExpression(variable.initializer) - && ts.isIdentifier(variable.initializer.left) - && ts.isClassLike(variable.initializer.right))); - } - function isTypeScriptClassWrapper(node) { - var call = ts.tryCast(node, ts.isCallExpression); - if (!call || ts.isParseTreeNode(call) || - ts.some(call.typeArguments) || - ts.some(call.arguments)) { - return false; - } - var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); - if (!func || ts.isParseTreeNode(func) || - ts.some(func.typeParameters) || - ts.some(func.parameters) || - func.type || - !func.body) { - return false; - } - var statements = func.body.statements; - if (statements.length < 2) { - return false; - } - var firstStatement = statements[0]; - if (ts.isParseTreeNode(firstStatement) || - !ts.isClassLike(firstStatement) && - !isClassLikeVariableStatement(firstStatement)) { - return false; - } - var lastStatement = ts.elementAt(statements, -1); - var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); - if (!returnStatement || - !returnStatement.expression || - !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { - return false; - } - return true; - } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) - || isTypeScriptClassWrapper(node); + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -57875,7 +58303,7 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { - if (isTypeScriptClassWrapper(node)) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } if (node.transformFlags & 64 /* ES2015 */) { @@ -57917,7 +58345,7 @@ var ts; // }()) // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. - var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); // The class statements are the statements generated by visiting the first statement of the // body (1), while all other statements are added to remainingStatements (2) var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); @@ -58820,7 +59248,6 @@ var ts; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; var renamedCatchVariables; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; @@ -58867,10 +59294,8 @@ var ts; if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } /** @@ -61437,6 +61862,7 @@ var ts; */ function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var umdHeader = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -61456,13 +61882,13 @@ var ts; ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ ts.createStatement(ts.createCall(ts.createIdentifier("define"), - /*typeArguments*/ undefined, [ + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), ts.createIdentifier("factory") - ])) + ]))) ]))) ], /*multiLine*/ true), @@ -61588,17 +62014,20 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - if (emitAsReturn) { - var statement = ts.createReturn(currentModuleInfo.exportEquals.expression); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression)); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536 /* NoComments */); - statements.push(statement); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } } } } @@ -62143,7 +62572,7 @@ var ts; return statements; } if (ts.hasModifier(decl, 1 /* Export */)) { - var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name; + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); } if (decl.name) { @@ -63352,7 +63781,8 @@ var ts; */ function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - return ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]); + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); } // // Top-Level or Nested Source Element Visitors @@ -67105,8 +67535,15 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } + // TODO: Should this just be `emit`? + // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 + function emitIfPresent(node) { + if (node) { + emit(node); + } + } function emit(node) { - pipelineEmitWithNotification(3 /* Unspecified */, node); + pipelineEmitWithNotification(4 /* Unspecified */, node); } function emitIdentifierName(node) { pipelineEmitWithNotification(2 /* IdentifierName */, node); @@ -67144,7 +67581,8 @@ var ts; case 0 /* SourceFile */: return pipelineEmitSourceFile(node); case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* Unspecified */: return pipelineEmitUnspecified(node); + case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4 /* Unspecified */: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -67155,6 +67593,11 @@ var ts; ts.Debug.assertNode(node, ts.isIdentifier); emitIdentifier(node); } + function emitMappedTypeParameter(node) { + emit(node.name); + write(" in "); + emit(node.constraint); + } function pipelineEmitUnspecified(node) { var kind = node.kind; // Reserved words @@ -67544,9 +67987,9 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -67561,7 +68004,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); write(";"); } @@ -67569,7 +68012,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -67578,7 +68021,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); @@ -67587,9 +68030,9 @@ var ts; function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.asteriskToken, "*"); + emitIfPresent(node.asteriskToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -67662,10 +68105,8 @@ var ts; } function emitTypeLiteral(node) { write("{"); - // If the literal is empty, do not add spaces between braces. - if (node.members.length > 0) { - emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); - } + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); write("}"); } function emitArrayType(node) { @@ -67712,13 +68153,14 @@ var ts; writeLine(); increaseIndent(); } - writeIfPresent(node.readonlyToken, "readonly "); + if (node.readonlyToken) { + emit(node.readonlyToken); + write(" "); + } write("["); - emit(node.typeParameter.name); - write(" in "); - emit(node.typeParameter.constraint); + pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); write("]"); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); @@ -67761,7 +68203,7 @@ var ts; } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } @@ -67770,30 +68212,19 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); - } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { - var properties = node.properties; - if (properties.length === 0) { - write("{}"); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); } - else { - var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; - if (indentedFlag) { - increaseIndent(); - } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, properties, 978 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); - if (indentedFlag) { - decreaseIndent(); - } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); } } function emitPropertyAccessExpression(node) { @@ -67880,7 +68311,8 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); emitWithPrefix(": ", node.type); - write(" =>"); + write(" "); + emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { write("delete "); @@ -67947,12 +68379,12 @@ var ts; var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); increaseIndentIf(indentBeforeQuestion, " "); - write("?"); + emit(node.questionToken); increaseIndentIf(indentAfterQuestion, " "); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); increaseIndentIf(indentBeforeColon, " "); - write(":"); + emit(node.colonToken); increaseIndentIf(indentAfterColon, " "); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); @@ -67962,7 +68394,8 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write(node.asteriskToken ? "yield*" : "yield"); + write("yield"); + emit(node.asteriskToken); emitExpressionWithPrefix(" ", node.expression); } function emitSpreadExpression(node) { @@ -68003,28 +68436,17 @@ var ts; // Statements // function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); - write(" "); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); - } - else { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); - emitBlockStatements(node); - // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); - } + writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); + writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } - function emitBlockStatements(node) { - if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - emitList(node, node.statements, 384 /* SingleLineBlockStatements */); - } - else { - emitList(node, node.statements, 65 /* MultiLineBlockStatements */); - } + function emitBlockStatements(node, forceSingleLine) { + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -68205,7 +68627,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.asteriskToken ? "function* " : "function "); + write("function"); + emitIfPresent(node.asteriskToken); + write(" "); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -68223,7 +68647,7 @@ var ts; if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3 /* Unspecified */, body, emitBlockCallback); + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -68233,7 +68657,7 @@ var ts; pushNameGenerationScope(); emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3 /* Unspecified */, body, emitBlockCallback); + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -68378,7 +68802,9 @@ var ts; } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + if (~node.flags & 512 /* GlobalAugmentation */) { + write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + } emit(node.name); var body = node.body; while (body.kind === 233 /* ModuleDeclaration */) { @@ -68390,16 +68816,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isEmptyBlock(node)) { - write("{ }"); - } - else { - pushNameGenerationScope(); - write("{"); - emitBlockStatements(node); - write("}"); - popNameGenerationScope(); - } + pushNameGenerationScope(); + write("{"); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + write("}"); + popNameGenerationScope(); } function emitCaseBlock(node) { writeToken(17 /* OpenBraceToken */, node.pos); @@ -68550,9 +68971,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { write("{"); - if (node.dotDotDotToken) { - write("..."); - } + emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); write("}"); } @@ -68600,13 +69019,12 @@ var ts; // Note: we can't use parentNode.end as such position includes statements. emitTrailingCommentsOfPosition(statements.pos); } + var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { write(" "); - emit(statements[0]); - } - else { - emitList(parentNode, statements, 81985 /* CaseOrDefaultClauseStatements */); + format &= ~(1 /* MultiLine */ | 64 /* Indented */); } + emitList(parentNode, statements, format); } function emitHeritageClause(node) { write(" "); @@ -68827,7 +69245,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emit(parameters[0]); + emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -68849,8 +69267,14 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + var isEmpty = isUndefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } return; } if (format & 7680 /* BracketsMask */) { @@ -68864,7 +69288,7 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { write(" "); } } @@ -68944,7 +69368,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -68983,11 +69407,6 @@ var ts; write(text); } } - function writeIfPresent(node, text) { - if (node) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -68997,7 +69416,7 @@ var ts; if (onBeforeEmitToken) { onBeforeEmitToken(node); } - writeTokenText(node.kind); + write(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } @@ -69151,10 +69570,6 @@ var ts; && !ts.nodeIsSynthesized(node2) && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } - function isSingleLineEmptyBlock(block) { - return !block.multiLine - && isEmptyBlock(block); - } function isEmptyBlock(block) { return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); @@ -69463,6 +69878,8 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; @@ -69473,7 +69890,7 @@ var ts; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; @@ -69680,7 +70097,7 @@ var ts; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -69704,7 +70121,7 @@ var ts; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; + var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -69729,9 +70146,9 @@ var ts; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { - var start = diagnostic.start, length_6 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_6), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -69739,12 +70156,12 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += ts.sys.newLine; + output += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -69754,7 +70171,7 @@ var ts; lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; + output += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; output += redForegroundEscapeSequence; @@ -69773,15 +70190,15 @@ var ts; output += lineContent.replace(/./g, "~"); } output += resetEscapeSequence; - output += ts.sys.newLine; + output += host.getNewLine(); } - output += ts.sys.newLine; + output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine; + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += host.getNewLine(); } return output; } @@ -69870,6 +70287,8 @@ var ts; ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); @@ -69936,12 +70355,11 @@ var ts; // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file if (!options.lib) { - processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); + processRootFile(getDefaultLibraryFileName(), /*isDefaultLib*/ true); } else { - var libDirectory_1 = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(host.getDefaultLibFileName(options)); ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(libDirectory_1, libFileName), /*isDefaultLib*/ true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true); }); } } @@ -69976,6 +70394,7 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, @@ -70267,7 +70686,7 @@ var ts; var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct @@ -70344,6 +70763,15 @@ var ts; function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (defaultLibraryPath && defaultLibraryPath.length !== 0) { + return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + } + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } @@ -70485,9 +70913,7 @@ var ts; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - return ts.isSourceFileJavaScript(sourceFile) - ? ts.filter(diagnostics, shouldReportDiagnostic) - : diagnostics; + return ts.filter(diagnostics, shouldReportDiagnostic); }); } /** @@ -70724,16 +71150,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.text === b.text; - } - function getTextOfLiteral(literal) { - return literal.text; + return a.kind === 9 /* StringLiteral */ + ? b.kind === 9 /* StringLiteral */ && a.text === b.text + : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -70789,7 +71214,7 @@ var ts; break; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; // TODO: GH#17347 + var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -70869,8 +71294,8 @@ var ts; } } /** This has side effects through `findSourceFile`. */ - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, /*packageId*/ undefined); }, function (diagnostic) { + function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -70942,7 +71367,7 @@ var ts; } }); if (packageId) { - var packageIdKey = packageId.name + "@" + packageId.version; + var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -70994,7 +71419,7 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, /*packageId*/ undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -71020,7 +71445,7 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents @@ -71038,7 +71463,7 @@ var ts; } else { // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -71068,8 +71493,7 @@ var ts; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. - var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); - var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); @@ -71080,7 +71504,8 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; @@ -71093,7 +71518,12 @@ var ts; var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. - var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -71429,7 +71859,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -71437,6 +71867,18 @@ var ts; ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); return names; } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } })(ts || (ts = {})); /// /// @@ -72431,7 +72873,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; // Notify key value set, if user asked for it if (jsonConversionNotifier && @@ -72471,7 +72913,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95 /* NullKeyword */: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword case 9 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { @@ -72536,6 +72978,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable if (option.type === "list") { return ts.isArray(value); } @@ -72720,6 +73164,15 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -72752,7 +73205,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -72764,7 +73217,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -72773,7 +73226,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -72790,7 +73243,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -72860,7 +73313,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -72882,7 +73336,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -73038,6 +73493,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -73060,6 +73517,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -73186,7 +73645,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -73871,25 +74330,24 @@ var ts; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { - switch (node.parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 264 /* EnumMember */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 233 /* ModuleDeclaration */: - return ts.getNameOfDeclaration(node.parent) === node; - case 180 /* ElementAccessExpression */: - return node.parent.argumentExpression === node; - case 144 /* ComputedPropertyName */: - return true; - } + switch (node.parent.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 261 /* PropertyAssignment */: + case 264 /* EnumMember */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 233 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 180 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 144 /* ComputedPropertyName */: + return true; + case 173 /* LiteralType */: + return node.parent.parent.kind === 171 /* IndexedAccessType */; } - return false; } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; function isExpressionOfExternalModuleImportEqualsDeclaration(node) { @@ -73969,6 +74427,28 @@ var ts; return "alias" /* alias */; case 283 /* JSDocTypedefTag */: return "type" /* typeElement */; + case 194 /* BinaryExpression */: + var kind = ts.getSpecialPropertyAssignmentKind(node); + var right = node.right; + switch (kind) { + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return "method" /* memberFunctionElement */; // instance method + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + default: { + ts.assertTypeIsNever(kind); + return "" /* unknown */; + } + } default: return "" /* unknown */; } @@ -74172,7 +74652,7 @@ var ts; return undefined; } var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); + var listItemIndex = ts.indexOfNode(children, node); return { listItemIndex: listItemIndex, list: list @@ -74954,7 +75434,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_7 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -74963,8 +75443,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_7, classification: convertClassification(type) }); - lastEnd = start + length_7; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -75517,6 +75997,7 @@ var ts; // specially. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` docCommentAndDiagnostics.jsDoc.parent = token; classifyJSDocComment(docCommentAndDiagnostics.jsDoc); return; @@ -75968,8 +76449,8 @@ var ts; continue; } var start = completePrefix.length; - var length_8 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -76263,7 +76744,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -76289,14 +76770,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -76319,7 +76800,7 @@ var ts; return; } uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true); + var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); if (displayName) { entries.push({ name: displayName, @@ -76330,11 +76811,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); if (!displayName) { return undefined; } @@ -76352,13 +76833,13 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { @@ -76438,7 +76919,7 @@ var ts; var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -76462,7 +76943,7 @@ var ts; var type = typeChecker.getTypeAtLocation(node.expression); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -76493,7 +76974,7 @@ var ts; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } - else if (type.flags & 32 /* StringLiteral */) { + else if (type.flags & 32 /* StringLiteral */ && !(type.flags & 256 /* EnumLiteral */)) { var name = type.value; if (!uniques.has(name)) { uniques.set(name, true); @@ -76510,12 +76991,12 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location = completionData.location; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); if (symbol) { var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { @@ -76546,11 +77027,15 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { @@ -76618,7 +77103,7 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -76705,6 +77190,7 @@ var ts; var semanticStart = ts.timestamp(); var isGlobalCompletion = false; var isMemberCompletion; + var allowStringLiteral = false; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; @@ -76740,7 +77226,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 277 /* JSDocAugmentsTag */: @@ -77073,6 +77559,7 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; + allowStringLiteral = true; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { @@ -77082,7 +77569,7 @@ var ts; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); existingMembers = objectLikeContainer.properties; } else { @@ -77641,7 +78128,7 @@ var ts; * * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { var name = symbol.name; if (!name) return undefined; @@ -77654,19 +78141,20 @@ var ts; return undefined; } } - return getCompletionEntryDisplayName(name, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } /** * Get a displayName from a given for completion list, performing any necessary quotes stripping * and checking whether the name is valid identifier name. */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return undefined; + // TODO: GH#18169 + return allowStringLiteral ? JSON.stringify(name) : undefined; } return name; } @@ -77773,6 +78261,20 @@ var ts; return node.parent; } } + /** + * Gets all properties on a type, but if that type is a union of several types, + * tries to only include those types which declare properties, not methods. + * This ensures that we don't try providing completions for all the methods on e.g. Array. + */ + function getPropertiesForCompletion(type, checker) { + if (!(type.flags & 65536 /* Union */)) { + return checker.getPropertiesOfType(type); + } + var types = type.types; + var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 /* Primitive */ || checker.isArrayLikeType(memberType)); }); + // If there are no property-only types, just provide completions for every type as usual. + return checker.getAllPossiblePropertiesOfTypes(filteredTypes); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -78365,12 +78867,11 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, - languageServiceRefCount: 0, + languageServiceRefCount: 1, owners: [] }; bucket.set(path, entry); @@ -78382,14 +78883,14 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); } - } - // If we're acquiring, then this is the first time this LS is asking for this document. - // Increase our ref count so we know there's another LS using the document. If we're - // not acquiring, then that means the LS is 'updating' the file instead, and that means - // it has already acquired the document previously. As such, we do not need to increase - // the ref count. - if (acquiring) { - entry.languageServiceRefCount++; + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } } return entry.sourceFile; } @@ -78571,7 +79072,6 @@ var ts; * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. */ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { @@ -78603,10 +79103,10 @@ var ts; searchForNamedImport(decl.exportClause); return; } - if (!decl.importClause) { + var importClause = decl.importClause; + if (!importClause) { return; } - var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { handleNamespaceImportLike(namedBindings.name); @@ -78626,7 +79126,6 @@ var ts; } // 'default' might be accessed as a named import `{ default as foo }`. if (!isForRename && exportKind === 1 /* Default */) { - ts.Debug.assert(exportName === "default"); searchForNamedImport(namedBindings); } } @@ -78638,35 +79137,40 @@ var ts; */ function handleNamespaceImportLike(importName) { // Don't rename an import that already has a different name than the export. - if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.escapedText === exportName)) { + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) { - for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).escapedText !== exportName) { - continue; - } - if (propertyName) { - // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. - singleReferences.push(propertyName); - if (!isForRename) { - // Search locally for `bar`. - addSearch(name, checker.getSymbolAtLocation(name)); - } - } - else { - var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName - ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. - : checker.getSymbolAtLocation(name); - addSearch(name, localSymbol); + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + if (!isForRename) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); } } + else { + var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } } } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; + } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { @@ -78842,7 +79346,8 @@ var ts; // Get the symbol for the `export =` node; its parent is the module it's the export of. var exportingModuleSymbol = ex.symbol.parent; ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -78874,7 +79379,11 @@ var ts; if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } - if (symbolName(importedSymbol) === symbol.escapedName) { + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = symbolName(importedSymbol); + if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } @@ -79066,8 +79575,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_2 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -79075,8 +79584,8 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; @@ -79117,8 +79626,10 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 79 /* DefaultKeyword */ + || ts.isAnyDeclarationName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -79160,7 +79671,7 @@ var ts; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; - var writeAccess = isWriteAccess(node); + var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, @@ -79179,20 +79690,8 @@ var ts; return ts.createTextSpanFromBounds(start, end); } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ - function isWriteAccess(node) { - if (ts.isAnyDeclarationName(node)) { - return true; - } - var parent = node.parent; - switch (parent && parent.kind) { - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: - return true; - case 194 /* BinaryExpression */: - return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); - default: - return false; - } + function isWriteAccessForReference(node) { + return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -79617,7 +80116,7 @@ var ts; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for - switch (node && node.kind) { + switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; case 9 /* StringLiteral */: @@ -79625,6 +80124,8 @@ var ts; node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 79 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; default: return false; } @@ -80237,20 +80738,24 @@ var ts; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); + addRootSymbols(bindingElementPropertySymbol); } - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - for (var _i = 0, _a = checker.getRootSymbols(symbol); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); + addRootSymbols(symbol); + return result; + function addRootSymbols(sym) { + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list + for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { + var rootSymbol = _a[_i]; + if (rootSymbol !== sym) { + result.push(rootSymbol); + } + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); + } } } - return result; } /** * Find symbol of the given property-name and add the symbol to the given result array @@ -80333,30 +80838,35 @@ var ts; // then include the binding element in the related symbols // let { a } : { a }; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); - if (bindingElementPropertySymbol && search.includes(bindingElementPropertySymbol)) { - return bindingElementPropertySymbol; - } - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.forEach(state.checker.getRootSymbols(referenceSymbol), function (rootSymbol) { - // if it is in the list, then we are done - if (search.includes(rootSymbol)) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the - // parent symbol - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { - return undefined; + if (bindingElementPropertySymbol) { + var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); + if (fromBindingElement) + return fromBindingElement; + } + return findRootSymbol(referenceSymbol); + function findRootSymbol(sym) { + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols + return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + // if it is in the list, then we are done + if (search.includes(rootSymbol)) { + return rootSymbol; + } + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the + // parent symbol + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + // Parents will only be defined if implementations is true + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + return undefined; + } + var result = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); + return ts.find(result, search.includes); } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); - return ts.find(result, search.includes); - } - return undefined; - }); + return undefined; + }); + } } function getNameFromObjectLiteralElement(node) { if (node.name.kind === 144 /* ComputedPropertyName */) { @@ -80979,52 +81489,32 @@ var ts; if (!tokenAtPos || tokenStart < position) { return undefined; } - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 229 /* ClassDeclaration */: - case 208 /* VariableStatement */: - break findOwner; - case 265 /* SourceFile */: - return undefined; - case 233 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 233 /* ModuleDeclaration */) { - return undefined; - } - break findOwner; - } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; } - if (!commentOwner || commentOwner.getStart() < position) { + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart() < position) { return undefined; } - var parameters = getParametersForJsDocOwningNode(commentOwner); var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; + if (parameters) { + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 /* Identifier */ ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } } // A doc comment consists of the following @@ -81043,18 +81533,46 @@ var ts; return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 208 /* VariableStatement */) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + function getCommentOwnerInfo(tokenAtPos) { + // TODO: add support for: + // - enums/enum members + // - interfaces + // - property declarations + // - potentially property assignments + for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 229 /* ClassDeclaration */: + return { commentOwner: commentOwner }; + case 208 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 265 /* SourceFile */: + return undefined; + case 233 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 233 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 194 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return undefined; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } } } - return ts.emptyArray; } /** * Digs into an an initializer or RHS operand of an assignment operation @@ -81303,32 +81821,7 @@ var ts; return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { - if (declarations) { - // First do a quick check to see if the name of the declaration matches the - // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { - return; // continue to next named declarations - } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - // It was a match! If the pattern has dots in it, then also see if the - // declaration container matches as well. - if (patternMatcher.patternContainsDots) { - var containers = getContainers(declaration); - if (!containers) { - return true; // Break out of named declarations and go to the next source file. - } - matches = patternMatcher.getMatches(containers, name); - if (!matches) { - return; // continue to next named declarations - } - } - var fileName = sourceFile.fileName; - var matchKind = bestMatchKind(matches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); - } - } + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] @@ -81336,134 +81829,159 @@ var ts; var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } - // Remove imports when the imported declaration is already in the list and has the same name. - rawItems = ts.filter(rawItems, function (item) { - var decl = item.declaration; - if (decl.kind === 239 /* ImportClause */ || decl.kind === 242 /* ImportSpecifier */ || decl.kind === 237 /* ImportEqualsDeclaration */) { - var importer = checker.getSymbolAtLocation(decl.name); - var imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName; - } - else { - return true; - } - }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); } - var items = ts.map(rawItems, createNavigateToItem); - return items; - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - if (!match.isCaseSensitive) { - return false; - } + return rawItems.map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); + if (!matches) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (!shouldKeepItem(declaration, checker)) { + continue; } - return true; - } - function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + // It was a match! If the pattern has dots in it, then also see if the + // declaration container matches as well. + var containerMatches = matches; + if (patternMatcher.patternContainsDots) { + containerMatches = patternMatcher.getMatches(getContainers(declaration), name); + if (!containerMatches) { + continue; } } - return true; + var matchKind = bestMatchKind(containerMatches); + var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); + rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); } - // Only added the names of computed properties if they're simple dotted expressions, like: - // - // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (text !== undefined) { - if (includeLastPortion) { - containers.unshift(text); - } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 239 /* ImportClause */: + case 242 /* ImportSpecifier */: + case 237 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: return true; + } + } + function allMatchesAreCaseSensitive(matches) { + ts.Debug.assert(matches.length > 0); + // This is a case sensitive match, only if all the submatches were case sensitive. + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; + if (!match.isCaseSensitive) { + return false; } - if (expression.kind === 179 /* PropertyAccessExpression */) { - var propertyAccess = expression; - if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); - } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); - } - return false; } - function getContainers(declaration) { - var containers = []; - // First, if we started with a computed property name, then add all but the last - // portion into the container array. + return true; + } + function tryAddSingleDeclarationName(declaration, containers) { + if (declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { - return undefined; + if (name) { + var text = ts.getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); } - } - // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; } - declaration = ts.getContainerNode(declaration); } - return containers; } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } + return true; + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers, includeLastPortion) { + var text = ts.getTextOfIdentifierOrLiteral(expression); + if (text !== undefined) { + if (includeLastPortion) { + containers.unshift(text); + } + return true; + } + if (expression.kind === 179 /* PropertyAccessExpression */) { + var propertyAccess = expression; + if (includeLastPortion) { + containers.unshift(propertyAccess.name.text); } - return bestMatchKind; + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } - function compareNavigateToItems(i1, i2) { - // TODO(cyrusn): get the gamut of comparisons that VS already uses here. - // Right now we just sort by kind first, and then by name of the item. - // We first sort case insensitively. So "Aaa" will come before "bar". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + return false; + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + return undefined; + } } - function createNavigateToItem(rawItem) { - var declaration = rawItem.declaration; - var container = ts.getContainerNode(declaration); - var containerName = container && ts.getNameOfDeclaration(container); - return { - name: rawItem.name, - kind: ts.getNodeKind(declaration), - kindModifiers: ts.getNodeModifiers(declaration), - matchKind: ts.PatternMatchKind[rawItem.matchKind], - isCaseSensitive: rawItem.isCaseSensitive, - fileName: rawItem.fileName, - textSpan: ts.createTextSpanFromNode(declaration), - // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ - }; + // Now, walk up our containers, adding all their names to the container array. + declaration = ts.getContainerNode(declaration); + while (declaration) { + if (!tryAddSingleDeclarationName(declaration, containers)) { + return undefined; + } + declaration = ts.getContainerNode(declaration); } + return containers; + } + function bestMatchKind(matches) { + ts.Debug.assert(matches.length > 0); + var bestMatchKind = ts.PatternMatchKind.camelCase; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; + var kind = match.kind; + if (kind < bestMatchKind) { + bestMatchKind = kind; + } + } + return bestMatchKind; + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + // Right now we just sort by kind first, and then by name of the item. + // We first sort case insensitively. So "Aaa" will come before "bar". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + return i1.matchKind - i2.matchKind || + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + }; } - NavigateTo.getNavigateToItems = getNavigateToItems; })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); /// @@ -81647,17 +82165,24 @@ var ts; break; case 176 /* BindingElement */: case 226 /* VariableDeclaration */: - var decl = node; - var name = decl.name; + var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); } - else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { - // For `const x = function() {}`, just use the function node, not the const. - addChildrenRecursively(decl.initializer); + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } } else { - addNodeWithRecursiveChild(decl, decl.initializer); + addNodeWithRecursiveChild(node, initializer); } break; case 187 /* ArrowFunction */: @@ -81667,8 +82192,8 @@ var ts; break; case 232 /* EnumDeclaration */: startNode(node); - for (var _d = 0, _e = node.members; _d < _e.length; _d++) { - var member = _e[_d]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -81679,8 +82204,8 @@ var ts; case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -81697,13 +82222,15 @@ var ts; addLeafNode(node); break; default: - ts.forEach(node.jsDoc, function (jsDoc) { - ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283 /* JSDocTypedefTag */) { - addLeafNode(tag); - } + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 283 /* JSDocTypedefTag */) { + addLeafNode(tag); + } + }); }); - }); + } ts.forEachChild(node, addChildrenRecursively); } } @@ -82038,7 +82565,14 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */ || node.kind === 199 /* ClassExpression */; + switch (node.kind) { + case 187 /* ArrowFunction */: + case 186 /* FunctionExpression */: + case 199 /* ClassExpression */: + return true; + default: + return false; + } } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); @@ -82049,11 +82583,15 @@ var ts; (function (OutliningElementsCollector) { var collapseText = "..."; var maxDepth = 20; + var defaultLabel = "#region"; + var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { var elements = []; var depth = 0; + var regions = []; walk(sourceFile); - return elements; + gatherRegions(); + return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { @@ -82122,6 +82660,36 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; } + function gatherRegions() { + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); + var comment = sourceFile.text.substring(currentLineStart, lineEnd); + var result = comment.match(regionMatch); + if (result && !ts.isInComment(sourceFile, currentLineStart)) { + if (!result[1]) { + var start = sourceFile.getFullText().indexOf("//", currentLineStart); + var textSpan = ts.createTextSpanFromBounds(start, lineEnd); + var region = { + textSpan: textSpan, + hintSpan: textSpan, + bannerText: result[2] || defaultLabel, + autoCollapse: false + }; + regions.push(region); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + elements.push(region); + } + } + } + } + } function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -83030,13 +83598,11 @@ var ts; } // skip open bracket token = nextToken(); - var i = 0; // scan until ']' or EOF while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names if (token === 9 /* StringLiteral */) { recordModuleName(); - i++; } token = nextToken(); } @@ -83197,10 +83763,16 @@ var ts; return ts.createTextSpan(start, width); } function nodeIsEligibleForRename(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - ts.isThis(node); + switch (node.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 99 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); @@ -83537,8 +84109,7 @@ var ts; if (isTypeParameterList) { isVariadic = false; // type parameter lists are not variadic prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - // Use `.mapper` to ensure we get the generic type arguments even if this is an instantiated version of the signature. - var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { @@ -83676,7 +84247,8 @@ var ts; if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { return "property" /* memberVariableElement */; } - ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); }); if (!unionPropertyKind) { // If this was union of all methods, @@ -84270,10 +84842,6 @@ var ts; (function (formatting) { var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); - /** - * Scanner that is currently used for formatting - */ - var scanner; var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -84283,9 +84851,8 @@ var ts; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); - function getFormattingScanner(text, languageVariant, startPos, endPos) { - ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); - scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; scanner.setText(text); scanner.setTextPos(startPos); var wasNewLine = true; @@ -84294,38 +84861,28 @@ var ts; var savedPos; var lastScanAction; var lastTokenInfo; - return { + var res = cb({ advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, - close: function () { - ts.Debug.assert(scanner !== undefined); - lastTokenInfo = undefined; - scanner.setText(undefined); - scanner = undefined; - } - }; + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; function advance() { - ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - if (trailingTrivia) { - ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; - } - else { - wasNewLine = false; - } + wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; } - leadingTrivia = undefined; - trailingTrivia = undefined; - if (!isStarted) { + else { scanner.scan(); } + leadingTrivia = undefined; + trailingTrivia = undefined; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { @@ -84341,23 +84898,18 @@ var ts; kind: t }; pos = scanner.getStartPos(); - if (!leadingTrivia) { - leadingTrivia = []; - } - leadingTrivia.push(item); + leadingTrivia = ts.append(leadingTrivia, item); } savedPos = scanner.getStartPos(); } function shouldRescanGreaterThanToken(node) { - if (node) { - switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - return true; - } + switch (node.kind) { + case 31 /* GreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + return true; } return false; } @@ -84368,13 +84920,14 @@ var ts; case 251 /* JsxOpeningElement */: case 252 /* JsxClosingElement */: case 250 /* JsxSelfClosingElement */: - return node.kind === 71 /* Identifier */; + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 10 /* JsxText */; + return node.kind === 10 /* JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 12 /* RegularExpressionLiteral */; @@ -84387,15 +84940,7 @@ var ts; return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; } function readTokenInfo(n) { - ts.Debug.assert(scanner !== undefined); - if (!isOnToken()) { - // scanner is not on the token (either advance was not called yet or scanner is already past the end position) - return { - leadingTrivia: leadingTrivia, - trailingTrivia: undefined, - token: undefined - }; - } + ts.Debug.assert(isOnToken()); // normally scanner returns the smallest available token // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. var expectedScanAction = shouldRescanGreaterThanToken(n) @@ -84424,32 +84969,7 @@ var ts; scanner.setTextPos(savedPos); scanner.scan(); } - var currentToken = scanner.getToken(); - if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 29 /* GreaterThanToken */) { - currentToken = scanner.reScanGreaterToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 1 /* RescanGreaterThanToken */; - } - else if (expectedScanAction === 2 /* RescanSlashToken */ && startsWithSlashToken(currentToken)) { - currentToken = scanner.reScanSlashToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 2 /* RescanSlashToken */; - } - else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 18 /* CloseBraceToken */) { - currentToken = scanner.reScanTemplateToken(); - lastScanAction = 3 /* RescanTemplateToken */; - } - else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 71 /* Identifier */) { - currentToken = scanner.scanJsxIdentifier(); - lastScanAction = 4 /* RescanJsxIdentifier */; - } - else if (expectedScanAction === 5 /* RescanJsxText */) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5 /* RescanJsxText */; - } - else { - lastScanAction = 0 /* Scan */; - } + var currentToken = getNextToken(n, expectedScanAction); var token = { pos: scanner.getStartPos(), end: scanner.getTextPos(), @@ -84482,8 +85002,46 @@ var ts; lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 29 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 18 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } function isOnToken() { - ts.Debug.assert(scanner !== undefined); var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); @@ -84623,11 +85181,6 @@ var ts; this.Operation = Operation; this.Flag = Flag; } - Rule.prototype.toString = function () { - return "[desc=" + this.Descriptor + "," + - "operation=" + this.Operation + "," + - "flag=" + this.Flag + "]"; - }; return Rule; }()); formatting.Rule = Rule; @@ -85021,16 +85574,16 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - } - Rules.prototype.getRuleName = function (rule) { - var o = this; - for (var name in o) { - if (o[name] === rule) { - return name; + if (ts.Debug.isDebugging) { + var o = this; + for (var name in o) { + var rule = o[name]; + if (rule instanceof formatting.Rule) { + rule.debugName = name; + } } } - throw new Error("Unknown rule"); - }; + } /// /// Contexts /// @@ -85188,8 +85741,8 @@ var ts; return true; case 207 /* Block */: { var blockParent = context.currentTokenParent.parent; - if (blockParent.kind !== 187 /* ArrowFunction */ && - blockParent.kind !== 186 /* FunctionExpression */) { + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 187 /* ArrowFunction */ && blockParent.kind !== 186 /* FunctionExpression */) { return true; } } @@ -85635,15 +86188,9 @@ var ts; var RulesProvider = /** @class */ (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); this.rulesMap = formatting.RulesMap.create(activeRules); } - RulesProvider.prototype.getRuleName = function (rule) { - return this.globalRules.getRuleName(rule); - }; - RulesProvider.prototype.getRuleByName = function (name) { - return this.globalRules[name]; - }; RulesProvider.prototype.getRulesMap = function () { return this.rulesMap; }; @@ -85918,8 +86465,8 @@ var ts; /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors - sourceFileLike); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { @@ -85935,7 +86482,7 @@ var ts; function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider @@ -85962,7 +86509,6 @@ var ts; trimTrailingWhitespacesForRemainingRange(); } } - formattingScanner.close(); return edits; // local functions /** Tries to compute the indentation for a list element. @@ -86201,6 +86747,7 @@ var ts; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; @@ -87120,6 +87667,8 @@ var ts; case 241 /* NamedImports */: case 246 /* ExportSpecifier */: case 242 /* ImportSpecifier */: + case 261 /* PropertyAssignment */: + case 149 /* PropertyDeclaration */: return true; } return false; @@ -87174,15 +87723,21 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - return n["__pos"]; + var result = n["__pos"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); n["__pos"] = pos; } function getEnd(n) { - return n["__end"]; + var result = n["__end"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); n["__end"] = end; } var Position; @@ -87237,7 +87792,9 @@ var ts; return position === Position.Start ? start : fullStart; } // get start position of the line following the line that contains fullstart position - var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + 1, sourceFile); + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); // skip whitespaces/newlines adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); @@ -87267,9 +87824,6 @@ var ts; } return s; } - function getNewlineKind(context) { - return context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - } var ChangeTracker = /** @class */ (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -87278,8 +87832,8 @@ var ts; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } - ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -87305,7 +87859,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(node); + var index = ts.indexOfNode(containingList, node); if (index < 0) { return this; } @@ -87430,7 +87984,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(after); + var index = ts.indexOfNode(containingList, after); if (index < 0) { return this; } @@ -87646,10 +88200,9 @@ var ts; var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); - printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); + printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - textChanges.getNonformattedText = getNonformattedText; function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { @@ -87660,7 +88213,6 @@ var ts; var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } - textChanges.applyFormatting = applyFormatting; function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -87675,13 +88227,10 @@ var ts; function assignPositionsToNode(node) { var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes - var newNode = ts.nodeIsSynthesized(visited) - ? visited - : (Proxy.prototype = visited, new Proxy()); + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); newNode.end = getEnd(node); return newNode; - function Proxy() { } } function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); @@ -87817,7 +88366,15 @@ var ts; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); if (actions && actions.length > 0) { - allActions = allActions.concat(actions); + for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { + var action = actions_1[_i]; + if (action === undefined) { + context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); + } + else { + allActions.push(action); + } + } } }); return allActions; @@ -87849,6 +88406,10 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextLength(context) { + return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + } + ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); /* @internal */ var ts; @@ -87868,7 +88429,7 @@ var ts; var leftText = qualifiedName.left.getText(sourceFile); var rightText = qualifiedName.right.getText(sourceFile); var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); return [{ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), @@ -88006,7 +88567,7 @@ var ts; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), @@ -88021,7 +88582,7 @@ var ts; return actions; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), @@ -88051,7 +88612,7 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); (actions || (actions = [])).push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), @@ -88069,7 +88630,7 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), @@ -88082,7 +88643,7 @@ var ts; if (token.parent.parent.kind === 181 /* CallExpression */) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? @@ -88225,7 +88786,7 @@ var ts; } } } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); changeTracker.deleteNode(sourceFile, superCall); return [{ @@ -88258,7 +88819,7 @@ var ts; if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); return [{ @@ -88292,7 +88853,7 @@ var ts; if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // We replace existing keywords with commas. for (var i = 1; i < heritageClauses.length; i++) { @@ -88323,7 +88884,7 @@ var ts; if (token.kind !== 71 /* Identifier */) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), @@ -88340,8 +88901,8 @@ var ts; (function (codefix) { codefix.registerCodeFix({ errorCodes: [ - ts.Diagnostics._0_is_declared_but_never_used.code, - ts.Diagnostics.Property_0_is_declared_but_never_used.code + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code ], getCodeActions: function (context) { var sourceFile = context.sourceFile; @@ -88491,19 +89052,19 @@ var ts; } } function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); } function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteRange(sourceFile, range)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); } function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeInList(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); } function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeRange(sourceFile, start, end)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); } function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { return { @@ -88527,11 +89088,32 @@ var ts; function getActionsForJSDocTypes(context) { var sourceFile = context.sourceFile; var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var decl = ts.findAncestor(node, function (n) { return n.kind === 226 /* VariableDeclaration */; }); + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + var decl = ts.findAncestor(node, function (n) { + return n.kind === 202 /* AsExpression */ || + n.kind === 155 /* CallSignature */ || + n.kind === 156 /* ConstructSignature */ || + n.kind === 228 /* FunctionDeclaration */ || + n.kind === 153 /* GetAccessor */ || + n.kind === 157 /* IndexSignature */ || + n.kind === 172 /* MappedType */ || + n.kind === 151 /* MethodDeclaration */ || + n.kind === 150 /* MethodSignature */ || + n.kind === 146 /* Parameter */ || + n.kind === 149 /* PropertyDeclaration */ || + n.kind === 148 /* PropertySignature */ || + n.kind === 154 /* SetAccessor */ || + n.kind === 231 /* TypeAliasDeclaration */ || + n.kind === 184 /* TypeAssertionExpression */ || + n.kind === 226 /* VariableDeclaration */; + }); if (!decl) return; var checker = context.program.getTypeChecker(); var jsdocType = decl.type; + if (!jsdocType) + return; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; @@ -88734,28 +89316,21 @@ var ts; if (cached) { return cached; } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); - } - } + var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); cachedImportDeclarations[moduleSymbolId] = existingDeclarations; return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; - } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - node = node.parent; + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238 /* ImportDeclaration */: + return parent; + case 248 /* ExternalModuleReference */: + return parent.parent; + default: + return undefined; } - return undefined; } } function getUniqueSymbolId(symbol) { @@ -89164,7 +89739,7 @@ var ts; } } function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + return ts.textChanges.ChangeTracker.fromContext(context); } function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { return { @@ -89251,7 +89826,7 @@ var ts; (function (codefix) { function newNodesToChanges(newNodes, insertAfter, context) { var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { var newNode = newNodes_1[_i]; changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); @@ -89538,7 +90113,7 @@ var ts; return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { @@ -89568,7 +90143,9 @@ var ts; deleteCallback(); } return { - edits: changeTracker.getChanges() + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined, }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } @@ -89730,7 +90307,7 @@ var ts; refactor.registerRefactor(extractMethod); /** Compute the associated code actions */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -89744,15 +90321,15 @@ var ts; var usedNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var extr = extractions_1[_i]; + var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; // Skip these since we don't have a way to report errors yet - if (extr.errors && extr.errors.length) { + if (errors.length) { continue; } // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); if (!usedNames.has(description)) { usedNames.set(description, true); actions.push({ @@ -89775,17 +90352,13 @@ var ts; }]; } function getEditsForAction(context, actionName) { - var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); var index = +parsedIndexMatch[1]; ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - var extractions = getPossibleExtractions(targetRange, context, index); - // Scope is no longer valid from when the user issued the refactor (??) - ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); - return ({ edits: extractions[0].changes }); + return getExtractionAtIndex(targetRange, context, index); } // Move these into diagnostic messages if they become user-facing var Messages; @@ -89818,15 +90391,19 @@ var ts; * The range is in a function which needs the 'static' modifier in a class */ RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; - })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + })(RangeFacts || (RangeFacts = {})); /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This * process may fail, in which case a set of errors is returned instead (these are currently * not shown to the user, but can be used by us diagnostically) */ + // exported only for tests function getRangeToExtract(sourceFile, span) { - var length = span.length || 0; + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + } // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); @@ -89893,22 +90470,13 @@ var ts; if (errors) { return { errors: errors }; } - // If our selection is the expression in an ExpressionStatement, expand - // the selection to include the enclosing Statement (this stops us - // from trying to care about the return value of the extracted function - // and eliminates double semicolon insertion in certain scenarios) - var range = ts.isStatement(start) - ? [start] - : start.parent && start.parent.kind === 210 /* ExpressionStatement */ - ? [start.parent] - : start; - return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; } function createErrorResult(sourceFile, start, length, message) { return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; } function checkRootNode(node) { - if (ts.isIdentifier(node)) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } return undefined; @@ -89946,7 +90514,7 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; } if (ts.isInAmbientContext(nodeToCheck)) { @@ -90010,45 +90578,30 @@ var ts; return false; } var savedPermittedJumps = permittedJumps; - if (node.parent) { - switch (node.parent.kind) { - case 211 /* IfStatement */: - if (node.parent.thenStatement === node || node.parent.elseStatement === node) { - // forbid all jumps inside thenStatement or elseStatement - permittedJumps = 0 /* None */; - } - break; - case 224 /* TryStatement */: - if (node.parent.tryBlock === node) { - // forbid all jumps inside try blocks - permittedJumps = 0 /* None */; - } - else if (node.parent.finallyBlock === node) { - // allow unconditional returns from finally blocks - permittedJumps = 4 /* Return */; - } - break; - case 260 /* CatchClause */: - if (node.parent.block === node) { - // forbid all jumps inside the block of catch clause - permittedJumps = 0 /* None */; - } - break; - case 257 /* CaseClause */: - if (node.expression !== node) { - // allow unlabeled break inside case clauses - permittedJumps |= 1 /* Break */; - } - break; - default: - if (ts.isIterationStatement(node.parent, /*lookInLabeledStatements*/ false)) { - if (node.parent.statement === node) { - // allow unlabeled break/continue inside loops - permittedJumps |= 1 /* Break */ | 2 /* Continue */; - } - } - break; - } + switch (node.kind) { + case 211 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 224 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 207 /* Block */: + if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 257 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; } switch (node.kind) { case 169 /* ThisType */: @@ -90074,7 +90627,7 @@ var ts; } } else { - if (!(permittedJumps & (218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); } @@ -90104,6 +90657,19 @@ var ts; } } extractMethod_1.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isPartOfExpression(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } function isValidExtractionTarget(node) { // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); @@ -90144,14 +90710,29 @@ var ts; } return scopes; } - extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + // exported only for tests + function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; + ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + } + extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; /** * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes * or an error explaining why we can't extract into that scope. */ - function getPossibleExtractions(targetRange, context, requestedChangesIndex) { - if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + // exported only for tests + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + return scopes.map(function (scope, i) { + return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + }); + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; if (targetRange === undefined) { return undefined; @@ -90161,87 +90742,67 @@ var ts; return undefined; } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; - context.cancellationToken.throwIfCancellationRequested(); - if (requestedChangesIndex !== undefined) { - if (errorsPerScope[requestedChangesIndex].length) { - return undefined; - } - return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; - } - else { - return scopes.map(function (scope, i) { - var errors = errorsPerScope[i]; - if (errors.length) { - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - errors: errors - }; - } - return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; - }); - } + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getDescriptionForScope(scope) { - if (ts.isFunctionLike(scope)) { - switch (scope.kind) { - case 152 /* Constructor */: - return "constructor"; - case 186 /* FunctionExpression */: - return scope.name - ? "function expression " + scope.name.getText() - : "anonymous function expression"; - case 228 /* FunctionDeclaration */: - return "function " + scope.name.getText(); - case 187 /* ArrowFunction */: - return "arrow function"; - case 151 /* MethodDeclaration */: - return "method " + scope.name.getText(); - case 153 /* GetAccessor */: - return "get " + scope.name.getText(); - case 154 /* SetAccessor */: - return "set " + scope.name.getText(); - } - } - else if (ts.isModuleBlock(scope)) { - return "namespace " + scope.parent.name.getText(); - } - else if (ts.isClassLike(scope)) { - return scope.kind === 229 /* ClassDeclaration */ - ? "class " + scope.name.text - : scope.name.text - ? "class expression " + scope.name.text - : "anonymous class expression"; - } - else if (ts.isSourceFile(scope)) { - return "file '" + scope.fileName + "'"; - } - else { - return "unknown"; + return ts.isFunctionLikeDeclaration(scope) + ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? "method in " + getDescriptionForClassLikeDeclaration(scope) + : "function in " + getDescriptionForModuleLikeDeclaration(scope); + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 152 /* Constructor */: + return "constructor"; + case 186 /* FunctionExpression */: + return scope.name + ? "function expression '" + scope.name.text + "'" + : "anonymous function expression"; + case 228 /* FunctionDeclaration */: + return "function '" + scope.name.text + "'"; + case 187 /* ArrowFunction */: + return "arrow function"; + case 151 /* MethodDeclaration */: + return "method '" + scope.name.getText(); + case 153 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 154 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + ts.Debug.assertNever(scope); } } - function getUniqueName(isNameOkay) { + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 229 /* ClassDeclaration */ + ? "class '" + scope.name.text + "'" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 234 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? "module scope" : "global scope"; + } + function getUniqueName(fileText) { var functionNameText = "newFunction"; - if (isNameOkay(functionNameText)) { - return functionNameText; - } - var i = 1; - while (!isNameOkay(functionNameText = "newFunction_" + i)) { - i++; + for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { + functionNameText = "newFunction_" + i; } return functionNameText; } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ function extractFunctionInScope(node, scope, _a, range, context) { - var usagesInScope = _a.usages, substitutions = _a.substitutions; + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var functionNameText = getUniqueName(file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var functionReference = ts.createIdentifier(functionNameText); var returnType = undefined; var parameters = []; var callArguments = []; @@ -90266,13 +90827,23 @@ var ts; } callArguments.push(ts.createIdentifier(name)); }); - // Provide explicit return types for contexutally-typed functions + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); returnType = checker.typeToTypeNode(contextualType); } - var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -90284,22 +90855,27 @@ var ts; modifiers.push(ts.createToken(120 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, - /*questionToken*/ undefined, - /*typeParameters*/ [], parameters, returnType, body); + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, - /*typeParameters*/ [], parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - // insert function at the end of the scope - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var newNodes = []; // replace range with function call - var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, - /*typeArguments*/ undefined, callArguments); + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); if (range.facts & RangeFacts.IsGenerator) { call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); } @@ -90323,6 +90899,9 @@ var ts; } else { newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } } } else { @@ -90355,67 +90934,164 @@ var ts; else { changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); } - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - changes: changeTracker.getChanges() - }; - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); - } - function generateReturnValueProperty() { - return "__return"; - } - function transformFunctionBody(body) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is - return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; - } - var returnValueProperty; - var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { - var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { - // add return at the end to propagate writes back in case if control flow falls out of the function body - // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); - if (assignments.length === 1) { - rewrittenStatements.push(ts.createReturn(assignments[0].name)); - } - else { - rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); - } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getRenameLocation(edits, renameFilename, functionNameText) { + var delta = 0; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { + var change = textChanges_2[_b]; + var span_17 = change.span, newText = change.newText; + // TODO(acasey): We are assuming that the call expression comes before the function declaration, + // because we want the new cursor to be on the call expression, + // which is closer to where the user was before extracting the function. + var index = newText.indexOf(functionNameText); + if (index !== -1) { + return span_17.start + delta + index; + } + delta += newText.length - span_17.length; + } + } + throw new Error(); // Didn't find the text we inserted? + } + function getFirstDeclaration(type) { + var firstDeclaration = undefined; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + if (declaration1) { + if (declaration2) { + var positionDiff = declaration1.pos - declaration2.pos; + if (positionDiff !== 0) { + return positionDiff; } - return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; } else { - return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; - } - function visitor(node) { - if (node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = generateReturnValueProperty(); - } - assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); - } - if (assignments.length === 1) { - return ts.createReturn(assignments[0].name); - } - else { - return ts.createReturn(ts.createObjectLiteral(assignments)); + return 1; // Sort undeclared type parameters to the front. + } + } + else if (declaration2) { + return -1; // Sort undeclared type parameters to the front. + } + var name1 = type1.symbol ? type1.symbol.getName() : ""; + var name2 = type2.symbol ? type2.symbol.getName() : ""; + var nameDiff = ts.compareStrings(name1, name2); + if (nameDiff !== 0) { + return nameDiff; + } + // IDs are guaranteed to be unique, so this ensures a total ordering. + return type1.id - type2.id; + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, writes, substitutions, hasReturn) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + // already block, no writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); } else { - var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return ts.createReturn(ts.createObjectLiteral(assignments)); } } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLike(scope)) { + var body = scope.body; + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertTypeIsNever(scope); } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + }); + } + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); } - extractMethod_1.extractFunctionInScope = extractFunctionInScope; function isReadonlyArray(v) { return ts.isArray(v); } @@ -90440,7 +91116,8 @@ var ts; // value should be passed to extracted method and propagated back Usage[Usage["Write"] = 2] = "Write"; })(Usage || (Usage = {})); - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID var usagesPerScope = []; var substitutionsPerScope = []; var errorsPerScope = []; @@ -90448,14 +91125,50 @@ var ts; // initialize results for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { var _ = scopes_1[_i]; - usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); errorsPerScope.push([]); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { + for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } var _loop_8 = function (i) { var hasWrite = false; var readonlyClassPropertyWrite = undefined; @@ -90473,7 +91186,7 @@ var ts; errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); } }; for (var i = 0; i < scopes.length; i++) { @@ -90485,8 +91198,38 @@ var ts; ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function hasTypeParameters(node) { + return ts.isDeclarationWithTypeParameters(node) && + node.typeParameters !== undefined && + node.typeParameters.length > 0; + } + function isInGenericContext(node) { + for (; node; node = node.parent) { + if (hasTypeParameters(node)) { + return true; + } + } + return false; + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.flags & 16384 /* TypeParameter */) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } if (ts.isDeclaration(node) && node.symbol) { visibleDeclarationsInExtractedRange.push(node.symbol); } @@ -90531,7 +91274,11 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = checker.getSymbolAtLocation(identifier); + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -90565,7 +91312,7 @@ var ts; if (!declInFile) { return undefined; } - if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { // declaration is located in range to be extracted - do nothing return undefined; } @@ -90589,7 +91336,11 @@ var ts; substitutionsPerScope[i].set(symbolId, substitution); } else if (isTypeName) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } } else { usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); @@ -91237,6 +91988,11 @@ var ts; } } break; + case 194 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through default: ts.forEachChild(node, visit); } @@ -91582,7 +92338,7 @@ var ts; oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || oldSettings.baseUrl !== newSettings.baseUrl || !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler @@ -91760,7 +92516,7 @@ var ts; /// Diagnostics function getSyntacticDiagnostics(fileName) { synchronizeHostData(); - return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } /** * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors @@ -91773,11 +92529,11 @@ var ts; // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { - return semanticDiagnostics; + return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); - return ts.concatenate(semanticDiagnostics, declarationDiagnostics); + return semanticDiagnostics.concat(declarationDiagnostics); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); @@ -91806,7 +92562,7 @@ var ts; return undefined; } var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { @@ -91841,6 +92597,20 @@ var ts; tags: displayPartsDocumentationsAndKind.tags }; } + function getSymbolAtLocationForQuickInfo(node, checker) { + if ((ts.isIdentifier(node) || ts.isStringLiteral(node)) + && ts.isPropertyAssignment(node.parent) + && node.parent.name === node) { + var type = checker.getContextualType(node.parent.parent); + if (type) { + var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; + } + } + } + return checker.getSymbolAtLocation(node); + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); @@ -91903,7 +92673,20 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = []; + if (options && options.isForRename) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + sourceFiles.push(sourceFile); + } + } + } + else { + sourceFiles = program.getSourceFiles().slice(); + } + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); @@ -92304,7 +93087,7 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: host.getNewLine(), + newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), rulesProvider: getRuleProvider(formatOptions), cancellationToken: cancellationToken }; @@ -92385,7 +93168,7 @@ var ts; nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } ts.forEachChild(node, walk); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; ts.forEachChild(jsDoc, walk); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 0b54986035c2f..4bce953f667ff 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -446,6 +446,9 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } + interface JSDocContainer { + } + type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | LabeledStatement | ExpressionStatement | VariableStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | EndOfFileToken; interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } @@ -458,7 +461,7 @@ declare namespace ts { type EqualsToken = Token; type AsteriskToken = Token; type EqualsGreaterThanToken = Token; - type EndOfFileToken = Token; + type EndOfFileToken = Token & JSDocContainer; type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; @@ -500,6 +503,7 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; + parent?: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { @@ -510,16 +514,18 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends NamedDeclaration { + interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SignatureDeclaration["kind"]; name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type?: TypeNode; + type: TypeNode | undefined; } - interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; + interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.CallSignature; } - interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; @@ -535,7 +541,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends NamedDeclaration { + interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -552,14 +558,14 @@ declare namespace ts { name: BindingName; initializer?: Expression; } - interface PropertySignature extends TypeElement { + interface PropertySignature extends TypeElement, JSDocContainer { kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } - interface PropertyDeclaration extends ClassElement { + interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; questionToken?: QuestionToken; name: PropertyName; @@ -571,27 +577,30 @@ declare namespace ts { name?: PropertyName; } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration; - interface PropertyAssignment extends ObjectLiteralElement { + interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.PropertyAssignment; name: PropertyName; questionToken?: QuestionToken; initializer: Expression; } - interface ShorthandPropertyAssignment extends ObjectLiteralElement { + interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } - interface SpreadAssignment extends ObjectLiteralElement { + interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { + parent: ObjectLiteralExpression; kind: SyntaxKind.SpreadAssignment; expression: Expression; } interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name?: DeclarationName; + name: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -619,7 +628,7 @@ declare namespace ts { * - MethodDeclaration * - AccessorDeclaration */ - interface FunctionLikeDeclarationBase extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclarationBase { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; @@ -632,16 +641,16 @@ declare namespace ts { name?: Identifier; body?: FunctionBody; } - interface MethodSignature extends SignatureDeclaration, TypeElement { + interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -651,20 +660,20 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; - interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { + interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode; } @@ -678,10 +687,10 @@ declare namespace ts { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclaration { + interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { + interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { kind: SyntaxKind.ConstructorType; } type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; @@ -692,6 +701,7 @@ declare namespace ts { } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; + parent?: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -736,7 +746,6 @@ declare namespace ts { } interface MappedTypeNode extends TypeNode, Declaration { kind: SyntaxKind.MappedType; - parent?: TypeAliasDeclaration; readonlyToken?: ReadonlyToken; typeParameter: TypeParameterDeclaration; questionToken?: QuestionToken; @@ -744,7 +753,7 @@ declare namespace ts { } interface LiteralTypeNode extends TypeNode { kind: SyntaxKind.LiteralType; - literal: Expression; + literal: BooleanLiteral | LiteralExpression | PrefixUnaryExpression; } interface StringLiteral extends LiteralExpression { kind: SyntaxKind.StringLiteral; @@ -879,12 +888,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -930,7 +939,7 @@ declare namespace ts { expression: Expression; literal: TemplateMiddle | TemplateTail; } - interface ParenthesizedExpression extends PrimaryExpression { + interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } @@ -940,6 +949,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; + parent?: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1107,11 +1117,11 @@ declare namespace ts { kind: SyntaxKind.Block; statements: NodeArray; } - interface VariableStatement extends Statement { + interface VariableStatement extends Statement, JSDocContainer { kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } - interface ExpressionStatement extends Statement { + interface ExpressionStatement extends Statement, JSDocContainer { kind: SyntaxKind.ExpressionStatement; expression: Expression; } @@ -1192,7 +1202,7 @@ declare namespace ts { statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; - interface LabeledStatement extends Statement { + interface LabeledStatement extends Statement, JSDocContainer { kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; @@ -1214,19 +1224,21 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; - interface ClassLikeDeclaration extends NamedDeclaration { + interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { + kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } - interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.ClassDeclaration; name?: Identifier; } - interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { kind: SyntaxKind.ClassExpression; } + type ClassLikeDeclaration = ClassDeclaration | ClassExpression; interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; @@ -1236,7 +1248,7 @@ declare namespace ts { name?: PropertyName; questionToken?: QuestionToken; } - interface InterfaceDeclaration extends DeclarationStatement { + interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; @@ -1249,26 +1261,26 @@ declare namespace ts { token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } - interface TypeAliasDeclaration extends DeclarationStatement { + interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends NamedDeclaration { + interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; initializer?: Expression; } - interface EnumDeclaration extends DeclarationStatement { + interface EnumDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleName = Identifier | StringLiteral; type ModuleBody = NamespaceBody | JSDocNamespaceBody; - interface ModuleDeclaration extends DeclarationStatement { + interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; parent?: ModuleBody | SourceFile; name: ModuleName; @@ -1295,7 +1307,7 @@ declare namespace ts { * - import x = require("mod"); * - import x = M.x; */ - interface ImportEqualsDeclaration extends DeclarationStatement { + interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; parent?: SourceFile | ModuleBlock; name: Identifier; @@ -1407,7 +1419,7 @@ declare namespace ts { kind: SyntaxKind.JSDocOptionalType; type: TypeNode; } - interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase { kind: SyntaxKind.JSDocFunctionType; } interface JSDocVariadicType extends JSDocType { @@ -1417,6 +1429,7 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; + parent?: HasJSDoc; tags: NodeArray | undefined; comment: string | undefined; } @@ -1472,7 +1485,6 @@ declare namespace ts { interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: ReadonlyArray; - jsDocTypeTag?: JSDocTypeTag; /** If true, then this type literal represents an *array* of its type. */ isArrayType?: boolean; } @@ -1547,10 +1559,10 @@ declare namespace ts { endOfFileToken: Token; fileName: string; text: string; - amdDependencies: AmdDependency[]; + amdDependencies: ReadonlyArray; moduleName: string; - referencedFiles: FileReference[]; - typeReferenceDirectives: FileReference[]; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; /** @@ -1566,7 +1578,7 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; - sourceFiles: SourceFile[]; + sourceFiles: ReadonlyArray; } interface JsonSourceFile extends SourceFile { jsonObject?: ObjectLiteralExpression; @@ -1589,7 +1601,7 @@ declare namespace ts { readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray): void; } class OperationCanceledException { } @@ -1602,11 +1614,11 @@ declare namespace ts { /** * Get a list of root file names that were passed to a 'createProgram' */ - getRootFileNames(): string[]; + getRootFileNames(): ReadonlyArray; /** * Get a list of files in the program */ - getSourceFiles(): SourceFile[]; + getSourceFiles(): ReadonlyArray; /** * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then * the JavaScript and declaration files will be produced for all the files in this program. @@ -1618,15 +1630,16 @@ declare namespace ts { * will be invoked when writing the JavaScript and declaration files. */ emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** - * Gets a type checker that can be used to semantically analyze source fils in the program. + * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; + isSourceFileFromExternalLibrary(file: SourceFile): boolean; } interface CustomTransformers { /** Custom transformers to evaluate before built-in transformations. */ @@ -1669,7 +1682,7 @@ declare namespace ts { interface EmitResult { emitSkipped: boolean; /** Contains declaration emit diagnostics */ - diagnostics: Diagnostic[]; + diagnostics: ReadonlyArray; emittedFiles: string[]; } interface TypeChecker { @@ -1970,6 +1983,7 @@ declare namespace ts { IndexedAccess = 524288, NonPrimitive = 16777216, Literal = 224, + Unit = 6368, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, StringLike = 262178, @@ -2172,7 +2186,7 @@ declare namespace ts { interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[]; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2372,6 +2386,11 @@ declare namespace ts { * If accessing a non-index file, this should include its name e.g. "foo/bar". */ name: string; + /** + * Name of a submodule within this package. + * May be "". + */ + subModuleName: string; /** Version of the package, e.g. "1.2.3" */ version: string; } @@ -2388,14 +2407,15 @@ declare namespace ts { interface ResolvedTypeReferenceDirective { primary: boolean; resolvedFileName?: string; + packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; failedLookupLocations: string[]; } interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; - getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; + getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -2460,7 +2480,8 @@ declare namespace ts { SourceFile = 0, Expression = 1, IdentifierName = 2, - Unspecified = 3, + MappedTypeParameter = 3, + Unspecified = 4, } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2639,6 +2660,9 @@ declare namespace ts { /** The version of the TypeScript compiler release */ const version: string; } +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; +} declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { @@ -2834,7 +2858,60 @@ declare namespace ts { * @returns The unescaped identifier text. */ function unescapeIdentifier(id: string): string; - function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; + function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; + function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node: Node): TypeNode | undefined; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ + function getJSDocReturnType(node: Node): TypeNode | undefined; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node: Node): ReadonlyArray | undefined; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3184,8 +3261,8 @@ declare namespace ts { function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode; - function createLiteralTypeNode(literal: Expression): LiteralTypeNode; - function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode; + function createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; + function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; @@ -3214,6 +3291,7 @@ declare namespace ts { function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -3231,8 +3309,13 @@ declare namespace ts { function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function createTemplateHead(text: string): TemplateHead; + function createTemplateMiddle(text: string): TemplateMiddle; + function createTemplateTail(text: string): TemplateTail; + function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; @@ -3388,10 +3471,12 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: SourceFile[]): Bundle; - function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createBundle(sourceFiles: ReadonlyArray): Bundle; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[]): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3575,8 +3660,8 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; getNewLine(): string; } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; + function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' @@ -3591,7 +3676,7 @@ declare namespace ts { * @param oldProgram - Reuses an old program structure. * @returns A 'Program' object. */ - function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; @@ -3700,7 +3785,7 @@ declare namespace ts { interface SourceFile { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; - getLineStarts(): number[]; + getLineStarts(): ReadonlyArray; getPositionOfLineAndCharacter(line: number, character: number): number; update(newText: string, textChangeRange: TextChangeRange): SourceFile; } @@ -3917,7 +4002,7 @@ declare namespace ts { * Represents a single refactoring action - for example, the "Extract Method..." refactor might * offer several actions, each corresponding to a surround class or closure to extract into. */ - type RefactorActionInfo = { + interface RefactorActionInfo { /** * The programmatic name of the refactoring action */ @@ -3928,16 +4013,16 @@ declare namespace ts { * so this description should make sense by itself if the parent is inlineable=true */ description: string; - }; + } /** * A set of edits to make in response to a refactor action, plus an optional * location where renaming should be invoked from */ - type RefactorEditInfo = { + interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename?: string; - renameLocation?: number; - }; + renameFilename: string | undefined; + renameLocation: number | undefined; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index f1356d558c67c..4128b5d17fa8f 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -800,6 +800,7 @@ var ts; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; /* @internal */ TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; @@ -1200,6 +1201,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1242,7 +1244,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); /*@internal*/ @@ -1349,6 +1352,15 @@ var ts; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); /* @internal */ (function (ts) { // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. @@ -1375,7 +1387,6 @@ var ts; return new MapCtr(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - /* @internal */ function createSymbolTable(symbols) { var result = createMap(); if (symbols) { @@ -2063,6 +2074,32 @@ var ts; return to; } ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ @@ -2236,11 +2273,6 @@ var ts; ts.getProperty = getProperty; /** * Gets the owned, enumerable property keys of a map-like. - * - * NOTE: This is intended for use with MapLike objects. For Map objects, use - * Object.keys instead as it offers better performance. - * - * @param map A map-like. */ function getOwnKeys(map) { var keys = []; @@ -2252,6 +2284,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2426,6 +2468,9 @@ var ts; /** Does nothing. */ function noop() { } ts.noop = noop; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -2503,12 +2548,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2768,21 +2812,13 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; - /* @internal */ function pathIsRelative(path) { return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2803,7 +2839,6 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; - /* @internal */ function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -2821,7 +2856,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3021,17 +3056,14 @@ var ts; return true; } ts.containsPath = containsPath; - /* @internal */ function startsWith(str, prefix) { return str.lastIndexOf(prefix, 0) === 0; } ts.startsWith = startsWith; - /* @internal */ function removePrefix(str, prefix) { return startsWith(str, prefix) ? str.substr(prefix.length) : str; } ts.removePrefix = removePrefix; - /* @internal */ function endsWith(str, suffix) { var expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; @@ -3045,7 +3077,6 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - /* @internal */ function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; @@ -3061,7 +3092,6 @@ var ts; // proof. var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - /* @internal */ ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -3551,6 +3581,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3617,7 +3651,6 @@ var ts; * Return an exact match if possible, or a pattern match, or undefined. * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) */ - /* @internal */ function matchPatternOrExact(patternStrings, candidate) { var patterns = []; for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { @@ -3634,7 +3667,6 @@ var ts; return findBestPatternMatch(patterns, function (_) { return _; }, candidate); } ts.matchPatternOrExact = matchPatternOrExact; - /* @internal */ function patternText(_a) { var prefix = _a.prefix, suffix = _a.suffix; return prefix + "*" + suffix; @@ -3644,14 +3676,12 @@ var ts; * Given that candidate matches pattern, returns the text matching the '*'. * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" */ - /* @internal */ function matchedText(pattern, candidate) { Debug.assert(isPatternMatch(pattern, candidate)); return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); } ts.matchedText = matchedText; /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ function findBestPatternMatch(values, getPattern, candidate) { var matchedValue = undefined; // use length of prefix as betterness criteria @@ -3673,7 +3703,6 @@ var ts; startsWith(candidate, prefix) && endsWith(candidate, suffix); } - /* @internal */ function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); @@ -3719,6 +3748,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); /// var ts; @@ -4320,8 +4355,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4641,7 +4676,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4714,6 +4751,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4831,7 +4869,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4936,17 +4974,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -5037,6 +5074,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5084,7 +5122,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); /// @@ -5364,7 +5402,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline } return res; } @@ -6889,7 +6927,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -6915,15 +6952,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -6957,7 +6993,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -7116,7 +7152,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while @@ -7157,6 +7193,19 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + /** + * Note: it is expected that the `nodeArray` and the `node` are within the same file. + * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. + */ + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 /* LessThan */ : bPos < aPos ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } /** * Gets flags that control emit behavior of a node. */ @@ -7191,6 +7240,7 @@ var ts; case 16 /* TemplateTail */: return "}" + escapeText(node.text, 96 /* backtick */) + "`"; case 8 /* NumericLiteral */: + case 12 /* RegularExpressionLiteral */: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -7304,6 +7354,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 273 /* JSDocFunctionType */: + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 282 /* JSDocTemplateTag */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { @@ -8029,59 +8107,62 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 99 /* ThisKeyword */: - var parent = node.parent; - switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 264 /* EnumMember */: - case 261 /* PropertyAssignment */: - case 176 /* BindingElement */: - return parent.initializer === node; - case 210 /* ExpressionStatement */: - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 219 /* ReturnStatement */: - case 220 /* WithStatement */: - case 221 /* SwitchStatement */: - case 257 /* CaseClause */: - case 223 /* ThrowStatement */: - return parent.expression === node; - case 214 /* ForStatement */: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || - forInStatement.expression === node; - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return node === parent.expression; - case 205 /* TemplateSpan */: - return node === parent.expression; - case 144 /* ComputedPropertyName */: - return node === parent.expression; - case 147 /* Decorator */: - case 256 /* JsxExpression */: - case 255 /* JsxSpreadAttribute */: - case 263 /* SpreadAssignment */: - return true; - case 201 /* ExpressionWithTypeArguments */: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 264 /* EnumMember */: + case 261 /* PropertyAssignment */: + case 176 /* BindingElement */: + return parent.initializer === node; + case 210 /* ExpressionStatement */: + case 211 /* IfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 219 /* ReturnStatement */: + case 220 /* WithStatement */: + case 221 /* SwitchStatement */: + case 257 /* CaseClause */: + case 223 /* ThrowStatement */: + return parent.expression === node; + case 214 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return node === parent.expression; + case 205 /* TemplateSpan */: + return node === parent.expression; + case 144 /* ComputedPropertyName */: + return node === parent.expression; + case 147 /* Decorator */: + case 256 /* JsxExpression */: + case 255 /* JsxSpreadAttribute */: + case 263 /* SpreadAssignment */: + return true; + case 201 /* ExpressionWithTypeArguments */: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; } @@ -8261,14 +8342,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -8276,15 +8349,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -8324,23 +8388,17 @@ var ts; } // Pull parameter comments from declaring function as well if (node.kind === 146 /* Parameter */) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - // a binding pattern doesn't have a name, so it's not possible to match it a jsdoc parameter, which is identified by name - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { @@ -8367,38 +8425,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); - if (!tag && node.kind === 146 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278 /* JSDocClassTag */); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -8410,7 +8436,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { return true; } } @@ -8848,9 +8874,9 @@ var ts; || kind === 265 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -9119,6 +9145,7 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" // nextLine }); + var escapedNullRegExp = /\\0[0-9]/g; /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -9128,9 +9155,12 @@ var ts; var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -9433,7 +9463,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -9446,7 +9476,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -9459,7 +9489,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -10127,6 +10157,45 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1 /* Write */; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0 /* Read */; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + /** Only reads from a variable. */ + AccessKind[AccessKind["Read"] = 0] = "Read"; + /** Only writes to a variable without using the result. E.g.: `x++;`. */ + AccessKind[AccessKind["Write"] = 1] = "Write"; + /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */ + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0 /* Read */; + switch (parent.kind) { + case 193 /* PostfixUnaryExpression */: + case 192 /* PrefixUnaryExpression */: + var operator = parent.operator; + return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; + case 194 /* BinaryExpression */: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; + case 179 /* PropertyAccessExpression */: + return parent.name !== node ? 0 /* Read */ : accessKind(parent); + default: + return 0 /* Read */; + } + function writeOrReadWrite() { + // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. + return parent.parent && parent.parent.kind === 210 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -10526,6 +10595,63 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + /** + * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should + * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol + * will be merged with) + */ + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + // Covers classes, functions - any named declaration host node + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + // Covers remaining cases + switch (hostNode.kind) { + case 208 /* VariableStatement */: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210 /* ExpressionStatement */: + var expr = hostNode.expression; + switch (expr.kind) { + case 179 /* PropertyAccessExpression */: + return expr.name; + case 180 /* ElementAccessExpression */: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1 /* EndOfFileToken */: + return undefined; + case 185 /* ParenthesizedExpression */: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222 /* LabeledStatement */: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -10545,11 +10671,124 @@ var ts; return undefined; } } + else if (declaration.kind === 283 /* JSDocTypedefTag */) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + /** + * Gets the JSDoc parameter tags for the node if present. + * + * @remarks Returns any JSDoc param tag that matches the provided + * parameter, whether a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the param + * tag on the containing function expression would be first. + * + * Does not return tags for binding patterns, because JSDoc matches + * parameters by name and binding patterns do not have a name. + */ + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Return true if the node has JSDoc parameter tags. + * + * @remarks Includes parameter tags that are not directly on the node, + * for example on a variable declaration whose initializer is a function expression. + */ + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + /** Gets the JSDoc augments tag for the node if present */ + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc class tag for the node if present */ + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + } + ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc return tag for the node if present */ + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + /** Gets the JSDoc template tag for the node if present */ + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + /** Gets the JSDoc type tag for the node if present and valid */ + function getJSDocTypeTag(node) { + // We should have already issued an error if there were multiple type jsdocs, so just use the first one. + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + /** + * Gets the type node for the node if provided via JSDoc. + * + * @remarks The search includes any JSDoc param tag that relates + * to the provided parameter, for example a type tag on the + * parameter itself, or a param tag on a containing function + * expression, or a param tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are examined first, so in the previous example, the type + * tag directly on the node would be returned. + */ + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); + if (!tag && node.kind === 146 /* Parameter */) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + /** + * Gets the return type node for the node if provided via JSDoc's return tag. + * + * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function + * gets the type from inside the braces. + */ + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + /** Get all JSDoc tags related to a node, including those on parent nodes. */ + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -11213,8 +11452,7 @@ var ts; // Node Arrays /* @internal */ function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; // Literals @@ -11310,16 +11548,28 @@ var ts; } ts.isFunctionLike = isFunctionLike; /* @internal */ - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152 /* Constructor */: - case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: + case 152 /* Constructor */: case 153 /* GetAccessor */: case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return true; + default: + return false; + } + } + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 150 /* MethodSignature */: case 155 /* CallSignature */: case 156 /* ConstructSignature */: case 157 /* IndexSignature */: @@ -11327,10 +11577,16 @@ var ts; case 273 /* JSDocFunctionType */: case 161 /* ConstructorType */: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + /* @internal */ + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; // Classes function isClassElement(node) { var kind = node.kind; @@ -11513,54 +11769,63 @@ var ts; || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 /* PropertyAccessExpression */ - || kind === 180 /* ElementAccessExpression */ - || kind === 182 /* NewExpression */ - || kind === 181 /* CallExpression */ - || kind === 249 /* JsxElement */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 183 /* TaggedTemplateExpression */ - || kind === 177 /* ArrayLiteralExpression */ - || kind === 185 /* ParenthesizedExpression */ - || kind === 178 /* ObjectLiteralExpression */ - || kind === 199 /* ClassExpression */ - || kind === 186 /* FunctionExpression */ - || kind === 71 /* Identifier */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 9 /* StringLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 196 /* TemplateExpression */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 91 /* ImportKeyword */ - || kind === 203 /* NonNullExpression */ - || kind === 204 /* MetaProperty */; - } /* @internal */ function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */ - || kind === 188 /* DeleteExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 190 /* VoidExpression */ - || kind === 191 /* AwaitExpression */ - || kind === 184 /* TypeAssertionExpression */ - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + case 182 /* NewExpression */: + case 181 /* CallExpression */: + case 249 /* JsxElement */: + case 250 /* JsxSelfClosingElement */: + case 183 /* TaggedTemplateExpression */: + case 177 /* ArrayLiteralExpression */: + case 185 /* ParenthesizedExpression */: + case 178 /* ObjectLiteralExpression */: + case 199 /* ClassExpression */: + case 186 /* FunctionExpression */: + case 71 /* Identifier */: + case 12 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 196 /* TemplateExpression */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 101 /* TrueKeyword */: + case 97 /* SuperKeyword */: + case 203 /* NonNullExpression */: + case 204 /* MetaProperty */: + case 91 /* ImportKeyword */:// technically this is only an Expression if it's in a CallExpression + return true; + default: + return false; + } } /* @internal */ function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192 /* PrefixUnaryExpression */: + case 193 /* PostfixUnaryExpression */: + case 188 /* DeleteExpression */: + case 189 /* TypeOfExpression */: + case 190 /* VoidExpression */: + case 191 /* AwaitExpression */: + case 184 /* TypeAssertionExpression */: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { @@ -11574,22 +11839,31 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 /* ConditionalExpression */ - || kind === 197 /* YieldExpression */ - || kind === 187 /* ArrowFunction */ - || kind === 194 /* BinaryExpression */ - || kind === 198 /* SpreadElement */ - || kind === 202 /* AsExpression */ - || kind === 200 /* OmittedExpression */ - || kind === 289 /* CommaListExpression */ - || isUnaryExpressionKind(kind); - } /* @internal */ + /** + * Determines whether a node is an expression based only on its kind. + * Use `isPartOfExpression` if not in transforms. + */ function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195 /* ConditionalExpression */: + case 197 /* YieldExpression */: + case 187 /* ArrowFunction */: + case 194 /* BinaryExpression */: + case 198 /* SpreadElement */: + case 202 /* AsExpression */: + case 200 /* OmittedExpression */: + case 289 /* CommaListExpression */: + case 288 /* PartiallyEmittedExpression */: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 /* TypeAssertionExpression */ @@ -11865,6 +12139,12 @@ var ts; return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; + /** True if has jsdoc nodes attached to it. */ + /* @internal */ + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); /// /// @@ -12301,9 +12581,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285 /* JSDocTypeLiteral */: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288 /* PartiallyEmittedExpression */: @@ -12599,7 +12881,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -12742,9 +13024,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } // Use this function to access the current token instead of reading the currentToken // variable. Since function results aren't narrowed in control flow analysis, this ensures // that the type checker doesn't make wrong assumptions about the type of the current @@ -12903,13 +13182,14 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + // Since the element list of a node array is typically created by starting with an empty array and + // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for + // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -12964,7 +13244,9 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + // Only for end of file because the error gets reported incorrectly on embedded script tags. + var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; + return createMissingNode(71 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -13246,20 +13528,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -13541,12 +13823,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26 /* CommaToken */)) { // No need to check for a zero length node since we know we parsed a comma @@ -13583,6 +13866,8 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); // Recording the trailing comma is deliberately done after the previous // loop, and not just if we see a list terminator. This is because the list // may have ended incorrectly, but it is still important to know if there @@ -13592,12 +13877,10 @@ var ts; // Always preserve a trailing comma by marking it on the NodeArray result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -13662,12 +13945,12 @@ var ts; var template = createNode(196 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -13779,7 +14062,7 @@ var ts; var result = createNode(273 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159 /* TypeReference */); node.typeName = parseIdentifierName(); @@ -13848,9 +14131,10 @@ var ts; return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 /* AtToken */ || isStartOfType(); + token() === 57 /* AtToken */ || + isStartOfType(/*inStartOfParameter*/ true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); @@ -13876,38 +14160,34 @@ var ts; } node.questionToken = parseOptionalToken(55 /* QuestionToken */); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ true); + node.initializer = parseInitializer(/*inParameter*/ true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(/*inParameter*/ true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36 /* EqualsGreaterThanToken */) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56 /* ColonToken */)) { + return true; } - else if (flags & 4 /* Type */) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 /* ColonToken */ ? 36 /* EqualsGreaterThanToken */ : 56 /* ColonToken */); - if (backwardToken) { - // This is easy to get backward, especially in type contexts, so parse the type anyway - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36 /* EqualsGreaterThanToken */) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { // FormalParameters [Yield,Await]: (modified) @@ -13928,7 +14208,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1 /* Yield */)); setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8 /* RequireCompleteParameterList */)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { @@ -14024,7 +14304,7 @@ var ts; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -14167,7 +14447,7 @@ var ts; parseExpected(94 /* NewKeyword */); } fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -14181,16 +14461,9 @@ var ts; unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } - var expression; - switch (token()) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - expression = parseLiteralLikeNode(token()); - break; - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - expression = parseTokenNode(); - } + var expression = token() === 101 /* TrueKeyword */ || token() === 86 /* FalseKeyword */ + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -14224,6 +14497,7 @@ var ts; return parseJSDocNodeWithType(274 /* JSDocVariadicType */); case 51 /* ExclamationToken */: return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: @@ -14255,7 +14529,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119 /* AnyKeyword */: case 136 /* StringKeyword */: @@ -14280,13 +14554,16 @@ var ts; case 86 /* FalseKeyword */: case 134 /* ObjectKeyword */: case 39 /* AsteriskToken */: + case 55 /* QuestionToken */: + case 51 /* ExclamationToken */: + case 24 /* DotDotDotToken */: return true; case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -14353,13 +14630,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -14545,7 +14821,7 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58 /* EqualsToken */) { // It's not uncommon during typing for the user to miss writing the '=' token. Check if // there is no newline after the last token and if we're on an expression. If so, parse @@ -14560,6 +14836,13 @@ var ts; // do not try to parse initializer return undefined; } + if (inParameter && requireEqualsToken) { + // = is required when speculatively parsing arrow function parameters, + // so return a fake initializer as a signal that the equals token was missing + var result = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } // Initializer[In, Yield] : // = AssignmentExpression[?In, ?Yield] @@ -14685,8 +14968,7 @@ var ts; var parameter = createNode(146 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); return addJSDocComment(finishNode(node)); @@ -14835,8 +15117,7 @@ var ts; function tryParseAsyncSimpleArrowFunctionExpression() { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === 120 /* AsyncKeyword */) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -14887,7 +15168,8 @@ var ts; // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + if (!allowAmbiguity && ((token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } @@ -15447,7 +15729,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { @@ -15467,12 +15750,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254 /* JsxAttributes */); @@ -16446,7 +16728,7 @@ var ts; var node = createNode(176 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingElement() { @@ -16462,7 +16744,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + node.initializer = parseInitializer(/*inParameter*/ false); return finishNode(node); } function parseObjectBindingPattern() { @@ -16496,7 +16778,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(/*inParameter*/ false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -16699,7 +16981,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57 /* AtToken */)) { @@ -16708,17 +16991,9 @@ var ts; var decorator = createNode(147 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); + (list || (list = [])).push(decorator); } - return decorators; + return list && createNodeArray(list, listPos); } /* * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. @@ -16728,7 +17003,8 @@ var ts; * In such situations, 'permitInvalidConstAsModifier' should be set to true. */ function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -16745,17 +17021,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); + (list || (list = [])).push(modifier); } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -16765,7 +17033,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -17323,11 +17590,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - // Parses out a JSDoc type expression. - /* @internal */ - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); - parseExpected(17 /* OpenBraceToken */); + if (!parseExpected(17 /* OpenBraceToken */) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); parseExpected(18 /* CloseBraceToken */); fixupParentReferences(result); @@ -17384,6 +17651,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; // Check for /** (JSDoc opening part) @@ -17507,7 +17776,7 @@ var ts; } function createJSDocComment() { var result = createNode(275 /* JSDocComment */, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -17637,21 +17906,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17 /* OpenBraceToken */) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' @@ -17743,11 +18008,11 @@ var ts; var result = createNode(281 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(/*requireBraces*/ true); var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -17784,19 +18049,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); } if (child.kind === 281 /* JSDocTypeTag */) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -17810,7 +18074,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -17905,7 +18171,8 @@ var ts; parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name = parseJSDocIdentifierName(); skipWhitespace(); @@ -17928,9 +18195,8 @@ var ts; var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -18072,7 +18338,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -18622,9 +18888,11 @@ var ts; symbol.flags |= symbolFlags; node.symbol = symbol; if (!symbol.declarations) { - symbol.declarations = []; + symbol.declarations = [node]; + } + else { + symbol.declarations.push(node); } - symbol.declarations.push(node); if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { symbol.exports = ts.createSymbolTable(); } @@ -18695,17 +18963,8 @@ var ts; var index = ts.indexOf(functionType.parameters, node); return "arg" + index; case 283 /* JSDocTypedefTag */: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (ts.isIdentifier(nameIdentifier)) { - nameFromParentNode = nameIdentifier.escapedText; - } - } - } - return nameFromParentNode; + var name_2 = ts.getNameOfJSDocTypedef(node); + return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; } } function getDisplayName(node) { @@ -18993,7 +19252,7 @@ var ts; // Binding of JsDocComment should be done before the current block scope container changes. // because the scope of JsDocComment should not be affected by whether the current node is a // container or not. - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { if (ts.isInJavaScriptFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; @@ -19795,10 +20054,6 @@ var ts; lastContainer = next; } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { switch (container.kind) { // Modules, source files, and classes need specialized handling for how their // members are declared (for example, a member of a class will go into a specific @@ -19995,6 +20250,9 @@ var ts; } function bindAnonymousDeclaration(node, symbolFlags, name) { var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & 8 /* EnumMember */) { + symbol.parent = container.symbol; + } addDeclarationToSymbol(symbol, node, symbolFlags); } function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { @@ -20205,7 +20463,7 @@ var ts; inStrictMode = saveInStrictMode; } function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { + if (!ts.hasJSDocNodes(node)) { return; } for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { @@ -21615,31 +21873,38 @@ var ts; return getSymbolWalker; function getSymbolWalker(accept) { if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = ts.createMap(); // Key is id as string - var visitedSymbols = ts.createMap(); // Key is id as string + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol return { walkType: function (type) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitType(type); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, walkSymbol: function (symbol) { - visitedTypes.clear(); - visitedSymbols.clear(); - visitSymbol(symbol); - return { visitedTypes: ts.arrayFrom(visitedTypes.values()), visitedSymbols: ts.arrayFrom(visitedSymbols.values()) }; + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } }, }; function visitType(type) { if (!type) { return; } - var typeIdString = type.id.toString(); - if (visitedTypes.has(typeIdString)) { + if (visitedTypes[type.id]) { return; } - visitedTypes.set(typeIdString, type); + visitedTypes[type.id] = type; // Reuse visitSymbol to visit the type's symbol, // but be sure to bail on recuring into the type if accept declines the symbol. var shouldBail = visitSymbol(type.symbol); @@ -21675,23 +21940,15 @@ var ts; visitIndexedAccessType(type); } } - function visitTypeList(types) { - if (!types) { - return; - } - for (var i = 0; i < types.length; i++) { - visitType(types[i]); - } - } function visitTypeReference(type) { visitType(type.target); - visitTypeList(type.typeArguments); + ts.forEach(type.typeArguments, visitType); } function visitTypeParameter(type) { visitType(getConstraintFromTypeParameter(type)); } function visitUnionOrIntersectionType(type) { - visitTypeList(type.types); + ts.forEach(type.types, visitType); } function visitIndexType(type) { visitType(type.type); @@ -21711,7 +21968,7 @@ var ts; if (signature.typePredicate) { visitType(signature.typePredicate.type); } - visitTypeList(signature.typeParameters); + ts.forEach(signature.typeParameters, visitType); for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; visitSymbol(parameter); @@ -21721,8 +21978,8 @@ var ts; } function visitInterfaceType(interfaceT) { visitObjectType(interfaceT); - visitTypeList(interfaceT.typeParameters); - visitTypeList(getBaseTypes(interfaceT)); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); visitType(interfaceT.thisType); } function visitObjectType(type) { @@ -21749,11 +22006,11 @@ var ts; if (!symbol) { return; } - var symbolIdString = ts.getSymbolId(symbol).toString(); - if (visitedSymbols.has(symbolIdString)) { + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { return; } - visitedSymbols.set(symbolIdString, symbol); + visitedSymbols[symbolId] = symbol; if (!accept(symbol)) { return true; } @@ -21813,7 +22070,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -21928,12 +22185,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -22333,7 +22590,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -22515,32 +22772,41 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -22588,9 +22854,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); @@ -22801,6 +23078,7 @@ var ts; var enumCount = 0; var symbolInstantiationDepth = 0; var emptySymbols = ts.createSymbolTable(); + var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var modulekind = ts.getEmitModuleKind(compilerOptions); @@ -22961,12 +23239,13 @@ var ts; return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); }, getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + isArrayLikeType: isArrayLikeType, + getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, getBaseConstraintOfType: getBaseConstraintOfType, resolveName: function (name, location, meaning) { - return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, }; @@ -23055,7 +23334,8 @@ var ts; var deferredUnusedIdentifierNodes; var flowLoopStart = 0; var flowLoopCount = 0; - var visitedFlowCount = 0; + var sharedFlowCount = 0; + var flowAnalysisDisabled = false; var emptyStringType = getLiteralType(""); var zeroType = getLiteralType(0); var resolutionTargets = []; @@ -23070,8 +23350,8 @@ var ts; var flowLoopNodes = []; var flowLoopKeys = []; var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; + var sharedFlowNodes = []; + var sharedFlowTypes = []; var potentialThisCollisions = []; var potentialNewTargetCollisions = []; var awaitedTypeStack = []; @@ -23205,6 +23485,7 @@ var ts; })(CheckMode || (CheckMode = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; function getJsxNamespace() { @@ -23288,7 +23569,7 @@ var ts; } function cloneSymbol(symbol) { var result = createSymbol(symbol.flags, symbol.escapedName); - result.declarations = symbol.declarations.slice(0); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -23387,6 +23668,7 @@ var ts; mergeSymbol(mainModule, moduleAugmentation.symbol); } else { + // moduleName will be a StringLiteral since this is not `declare global`. error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); } } @@ -23555,13 +23837,17 @@ var ts; }); } } - // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and - // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with - // the given name can be found. - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, suggestedNameNotFoundMessage) { - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, getSymbol, suggestedNameNotFoundMessage); + /** + * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + * the given name can be found. + * + * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. + */ + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, suggestedNameNotFoundMessage) { + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, getSymbol, suggestedNameNotFoundMessage); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, lookup, suggestedNameNotFoundMessage) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, lookup, suggestedNameNotFoundMessage) { var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; var lastLocation; @@ -23780,10 +24066,16 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { + if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastLocation.symbol) { result.isReferenced = true; } if (!result) { + if (lastLocation) { + ts.Debug.assert(lastLocation.kind === 265 /* SourceFile */); + if (lastLocation.commonJsModuleIndicator && name === "exports") { + return lastLocation.symbol; + } + } result = lookup(globals, name, meaning); } if (!result) { @@ -23917,7 +24209,7 @@ var ts; } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -23941,7 +24233,7 @@ var ts; error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; @@ -23951,14 +24243,14 @@ var ts; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -23991,11 +24283,17 @@ var ts; return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); + case 239 /* ImportClause */: + return node.parent; + case 240 /* NamespaceImport */: + return node.parent.parent; + case 242 /* ImportSpecifier */: + return node.parent.parent.parent; + default: + return undefined; } } function getDeclarationOfAliasSymbol(symbol) { @@ -24248,7 +24546,7 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, /*isUse*/ true); if (!symbol) { return undefined; } @@ -24295,7 +24593,7 @@ var ts; undefined; } else { - ts.Debug.fail("Unknown entity name kind."); + ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -24346,13 +24644,13 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -24465,10 +24763,9 @@ var ts; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + if (!(symbol && symbol.flags & 1952 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { return; } - visitedSymbols.push(symbol); var symbols = ts.cloneMap(symbol.exports); // All export * declarations are collected in an __export symbol by the binder var exportStars = symbol.exports.get("__export" /* ExportStar */); @@ -24616,65 +24913,61 @@ var ts; return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) { + return undefined; } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { + var visitedSymbolTables = []; + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + function getAccessibleSymbolChainFromSymbolTable(symbols) { + if (!ts.pushIfUnique(visitedSymbolTables, symbols)) { return undefined; } - visitedSymbolTables.push(symbols); var result = trySymbolTable(symbols); visitedSymbolTables.pop(); return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } + } + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) || // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolFromSymbolTable or alias resolution matches the symbol, - // check the symbol can be qualified, it is only then this symbol is accessible - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.escapedName))) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 2097152 /* Alias */ - && symbolFromSymbolTable.escapedName !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || // We can use any type of alias to get the name - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } + !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + return symbol === (resolvedAliasSymbol || symbolFromSymbolTable) && + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + function isUMDExportSymbol(symbol) { + return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + } + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */) + && !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) + // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } - }); - } - } - if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + }); } } function needsQualification(symbol, enclosingDeclaration, meaning) { @@ -24813,14 +25106,7 @@ var ts; // since we will do the emitting later in trackSymbol. if (shouldComputeAliasToMakeVisible) { getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); } return true; } @@ -24848,7 +25134,7 @@ var ts; meaning = 793064 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, @@ -24882,7 +25168,7 @@ var ts; var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; if (maxLength && result.length >= maxLength) { @@ -25174,14 +25460,14 @@ var ts; var i = 0; var qualifiedName = void 0; if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -25457,29 +25743,6 @@ var ts; } } } - function getNameOfSymbol(symbol, context) { - var declaration = ts.firstOrUndefined(symbol.declarations); - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { - return ts.declarationNameToString(declaration.parent.name); - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { - context.encounteredError = true; - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } - } - return ts.unescapeLeadingUnderscores(symbol.escapedName); - } } function typePredicateToString(typePredicate, enclosingDeclaration, flags) { return ts.usingSingleLineStringWriter(function (writer) { @@ -25537,9 +25800,9 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } - function getNameOfSymbol(symbol) { + function getNameOfSymbol(symbol, context) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -25549,6 +25812,9 @@ var ts; if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } + if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + context.encounteredError = true; + } switch (declaration.kind) { case 199 /* ClassExpression */: return "(Anonymous class)"; @@ -25557,6 +25823,12 @@ var ts; return "(Anonymous function)"; } } + if (symbol.syntheticLiteralTypeOrigin) { + var stringValue = symbol.syntheticLiteralTypeOrigin.value; + if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { + return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; + } + } return ts.unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder() { @@ -25794,14 +26066,14 @@ var ts; var outerTypeParameters = type.target.outerTypeParameters; var i = 0; if (outerTypeParameters) { - var length_3 = outerTypeParameters.length; - while (i < length_3) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -26349,7 +26621,7 @@ var ts; function collectLinkedAliases(node) { var exportSymbol; if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node, /*isUse*/ false); } else if (node.parent.kind === 246 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); @@ -26363,14 +26635,12 @@ var ts; ts.forEach(declarations, function (declaration) { getNodeLinks(declaration).isVisible = true; var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } + ts.pushIfUnique(result, resultNode); if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -26393,8 +26663,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_4 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_4; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -27104,38 +27374,50 @@ var ts; for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } + typeParameters = ts.appendIfUnique(typeParameters, tp); } return typeParameters; } - // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function - // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and - // returns the same array. - function appendOuterTypeParameters(typeParameters, node) { + // Return the outer type parameters of a node or undefined if the node has no outer type parameters. + function getOuterTypeParameters(node, includeThisTypes) { while (true) { node = node.parent; if (!node) { - return typeParameters; + return undefined; } - if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || - node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } + switch (node.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 273 /* JSDocFunctionType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 231 /* TypeAliasDeclaration */: + case 282 /* JSDocTemplateTag */: + case 172 /* MappedType */: + var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); + if (node.kind === 172 /* MappedType */) { + return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); + } + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var thisType = includeThisTypes && + (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || node.kind === 230 /* InterfaceDeclaration */) && + getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } } } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); + return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, // interface, or type alias. @@ -27189,7 +27471,7 @@ var ts; function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -27280,7 +27562,7 @@ var ts; var valueDecl = type.symbol.valueDeclaration; if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { + if (augTag && augTag.typeExpression && augTag.typeExpression.type) { baseType = getTypeFromTypeNode(augTag.typeExpression.type); } } @@ -27410,7 +27692,9 @@ var ts; var declaration = ts.find(symbol.declarations, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); - var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); + var typeNode = declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + // If typeNode is missing, we will error in checkJSDocTypedefTag. + var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -27761,7 +28045,7 @@ var ts; var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); var typeParamCount = ts.length(baseSig.typeParameters); if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -27798,9 +28082,7 @@ var ts; if (!match) { return undefined; } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } + result = ts.appendIfUnique(result, match); } return result; } @@ -28009,7 +28291,14 @@ var ts; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { + function addMemberForKeyType(t, propertySymbolOrIndex) { + var propertySymbol; + // forEachType delegates to forEach, which calls with a numeric second argument + // the type system currently doesn't catch this incompatibility, so we annotate + // the function ourselves to indicate the runtime behavior and deal with it here + if (typeof propertySymbolOrIndex === "object") { + propertySymbol = propertySymbolOrIndex; + } // Create a mapper from T to the current iteration type constituent. Then, if the // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. @@ -28029,6 +28318,7 @@ var ts; prop.syntheticOrigin = propertySymbol; prop.declarations = propertySymbol.declarations; } + prop.syntheticLiteralTypeOrigin = t; members.set(propName, prop); } else if (t.flags & 2 /* String */) { @@ -28151,26 +28441,22 @@ var ts; getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } - function getAllPossiblePropertiesOfType(type) { - if (type.flags & 65536 /* Union */) { - var props = ts.createSymbolTable(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var memberType = _a[_i]; - if (memberType.flags & 8190 /* Primitive */) { - continue; - } - for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { - var escapedName = _c[_b].escapedName; - if (!props.has(escapedName)) { - props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); - } + function getAllPossiblePropertiesOfTypes(types) { + var unionType = getUnionType(types); + if (!(unionType.flags & 65536 /* Union */)) { + return getPropertiesOfType(unionType); + } + var props = ts.createSymbolTable(); + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var memberType = types_2[_i]; + for (var _a = 0, _b = getPropertiesOfType(memberType); _a < _b.length; _a++) { + var escapedName = _b[_a].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(unionType, escapedName)); } } - return ts.arrayFrom(props.values()); - } - else { - return getPropertiesOfType(type); } + return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : @@ -28237,8 +28523,8 @@ var ts; if (t.flags & 196608 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type_2 = types_2[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type_2 = types_3[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -28316,20 +28602,15 @@ var ts; var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; var checkFlags = 0; - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var current = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var current = types_4[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } + props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | @@ -28479,12 +28760,7 @@ var ts; var result; ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - if (!result) { - result = []; - } - result.push(tp); - } + result = ts.appendIfUnique(result, tp); }); return result; } @@ -28520,7 +28796,7 @@ var ts; if (ts.isExternalModuleNameRelative(moduleName)) { return undefined; } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); // merged symbol is module declaration symbol combined with all augmentations return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } @@ -28583,11 +28859,10 @@ var ts; * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScript) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { if (!typeArguments) { typeArguments = []; @@ -28626,7 +28901,7 @@ var ts; var paramSymbol = param.symbol; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -28822,8 +29097,8 @@ var ts; } return anyType; } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + function getSignatureInstantiation(signature, typeArguments, isJavascript) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -28836,12 +29111,27 @@ var ts; return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); - } - return signature.erasedSignatureCache; + return signature.typeParameters ? + signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : + signature; + } + function createErasedSignature(signature) { + // Create an instantiation of the signature where all type arguments are the any type. + return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + function getCanonicalSignature(signature) { + return signature.typeParameters ? + signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) : + signature; + } + function createCanonicalSignature(signature) { + // Create an instantiation of the signature where each unconstrained type parameter is replaced with + // its original. When a generic class or interface is instantiated, each generic method in the class or + // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios + // where different generations of the same type parameter are in scope). This leads to a lot of new type + // identities, and potentially a lot of work comparing those identities, so here we create an instantiation + // that uses the original type identities for all unconstrained type parameters. + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); } function getOrCreateTypeFromSignature(signature) { // There are two ways to declare a construct signature, one is by declaring a class constructor @@ -28911,12 +29201,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_5 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_5) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_5 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -28937,8 +29227,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (!(type.flags & excludeKinds)) { result |= type.flags; } @@ -28977,7 +29267,8 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + var isJavascript = ts.isInJavaScriptFile(node); + if (!isJavascript && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); @@ -28986,7 +29277,7 @@ var ts; // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters // of the class or interface. - var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, node)); + var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJavascript)); return createTypeReference(type, typeArguments); } if (node.typeArguments) { @@ -29002,7 +29293,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); } return instantiation; } @@ -29214,7 +29505,8 @@ var ts; return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); + // Don't track references for global symbols anyway, so value if `isReference` is arbitrary + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -29374,6 +29666,22 @@ var ts; function containsType(types, type) { return binarySearchTypes(types, type) >= 0; } + // Return true if the given intersection type contains (a) more than one unit type or (b) an object + // type and a nullable type (null or undefined). + function isEmptyIntersectionType(type) { + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6368 /* Unit */ && combined & 6368 /* Unit */) { + return true; + } + combined |= t.flags; + if (combined & 6144 /* Nullable */ && combined & (32768 /* Object */ | 16777216 /* NonPrimitive */)) { + return true; + } + } + return false; + } function addTypeToUnion(typeSet, type) { var flags = type.flags; if (flags & 65536 /* Union */) { @@ -29390,7 +29698,11 @@ var ts; if (!(flags & 2097152 /* ContainsWideningType */)) typeSet.containsNonWideningType = true; } - else if (!(flags & 8192 /* Never */)) { + else if (!(flags & 8192 /* Never */ || flags & 131072 /* Intersection */ && isEmptyIntersectionType(type))) { + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. if (flags & 2 /* String */) typeSet.containsString = true; if (flags & 4 /* Number */) @@ -29410,14 +29722,14 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, types) { - for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { - var type = types_5[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; addTypeToUnion(typeSet, type); } } function containsIdenticalType(types, type) { - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -29425,8 +29737,8 @@ var ts; return false; } function isSubtypeOfAny(candidate, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } @@ -29519,6 +29831,12 @@ var ts; type = createType(65536 /* Union */ | propagatedFlags); unionTypes.set(id, type); type.types = types; + /* + Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. + For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. + (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.) + It's important that we create equivalent union types only once, so that's an unfortunate side effect. + */ type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = aliasTypeArguments; } @@ -29560,8 +29878,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; addTypeToIntersection(typeSet, type); } } @@ -29608,7 +29926,7 @@ var ts; type = createType(131072 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; - type.aliasSymbol = aliasSymbol; + type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. type.aliasTypeArguments = aliasTypeArguments; } return type; @@ -29720,21 +30038,6 @@ var ts; } return anyType; } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - if (accessNode) { - // Check if the index type is assignable to 'keyof T' for the object type. - if (!isTypeAssignableTo(indexType, getIndexType(type))) { - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); - return unknownType; - } - if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { - error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - } - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } function isGenericObjectType(type) { return type.flags & 540672 /* TypeVariable */ ? true : getObjectFlags(type) & 32 /* Mapped */ ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : @@ -29757,12 +30060,14 @@ var ts; } return false; } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. + // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return + // undefined if no transformation is possible. function getTransformedIndexedAccessType(type) { var objectType = type.objectType; + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. if (objectType.flags & 131072 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { var regularTypes = []; var stringIndexTypes = []; @@ -29780,19 +30085,22 @@ var ts; getIntersectionType(stringIndexTypes) ]); } - return undefined; - } - function getIndexedAccessType(objectType, indexType, accessNode) { - // If the object type is a mapped type { [P in K]: E }, where K is generic, we instantiate E using a mapper + // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - // Otherwise, if the index type is generic, or if the object type is generic and doesn't originate in an - // expression, we are performing a higher-order index access where we cannot meaningfully access the properties - // of the object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates - // in an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + return undefined; + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, or if the object type is generic and doesn't originate in an expression, + // we are performing a higher-order index access where we cannot meaningfully access the properties of the + // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in + // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { if (objectType.flags & 1 /* Any */) { @@ -29807,8 +30115,10 @@ var ts; return type; } // In the following we resolve T[K] to the type of the property in T selected by K. + // We treat boolean as different from other unions to improve errors; + // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -29892,7 +30202,10 @@ var ts; return mapType(right, function (t) { return getSpreadType(left, t); }); } if (right.flags & 16777216 /* NonPrimitive */) { - return emptyObjectType; + return nonPrimitiveType; + } + if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 262178 /* StringLike */ | 272 /* EnumLike */)) { + return left; } var members = ts.createSymbolTable(); var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); @@ -30120,10 +30433,6 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } function makeUnaryTypeMapper(source, target) { return function (t) { return t === source ? target : t; }; } @@ -30142,11 +30451,9 @@ var ts; } function createTypeMapper(sources, targets) { ts.Debug.assert(targets === undefined || sources.length === targets.length); - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -30156,9 +30463,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; + return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -30168,18 +30473,11 @@ var ts; createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } - function identityMapper(type) { - return type; - } function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; + return function (t) { return instantiateType(mapper1(t), mapper2); }; } function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; + return function (t) { return t === source ? target : baseMapper(t); }; } function cloneTypeParameter(typeParameter) { var result = createType(16384 /* TypeParameter */); @@ -30246,15 +30544,57 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } + if (symbol.isRestParameter) { + result.isRestParameter = symbol.isRestParameter; + } return result; } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); - result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; - result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; + function getAnonymousTypeInstantiation(type, mapper) { + var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + var symbol = target.symbol; + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (!typeParameters) { + // The first time an anonymous type is instantiated we compute and store a list of the type + // parameters that are in scope (and therefore potentially referenced). For type literals that + // aren't the right hand side of a generic type alias declaration we optimize by reducing the + // set of type parameters to those that are actually referenced somewhere in the literal. + var declaration_1 = symbol.declarations[0]; + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; + typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? + ts.filter(outerTypeParameters, function (tp) { return isTypeParameterReferencedWithin(tp, declaration_1); }) : + outerTypeParameters; + links.typeParameters = typeParameters; + if (typeParameters.length) { + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), target); + } + } + if (typeParameters.length) { + // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the + // mapper to the type parameters to produce the effective list of type arguments, and compute the + // instantiation cache key from the type IDs of the type arguments. + var combinedMapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + var typeArguments = ts.map(typeParameters, combinedMapper); + var id = getTypeListId(typeArguments); + var result = links.instantiations.get(id); + if (!result) { + var newMapper = createTypeMapper(typeParameters, typeArguments); + result = target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) : instantiateAnonymousType(target, newMapper); + links.instantiations.set(id, result); + } + return result; + } + return type; + } + function isTypeParameterReferencedWithin(tp, node) { + return tp.isThisType ? ts.forEachChild(node, checkThis) : ts.forEachChild(node, checkIdentifier); + function checkThis(node) { + return node.kind === 169 /* ThisType */ || ts.forEachChild(node, checkThis); + } + function checkIdentifier(node) { + return node.kind === 71 /* Identifier */ && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp || ts.forEachChild(node, checkIdentifier); + } } function instantiateMappedType(type, mapper) { // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some @@ -30270,161 +30610,62 @@ var ts; if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + return instantiateAnonymousType(type, createReplacementMapper(typeVariable_1, t, mapper)); } return t; }); } } } - return instantiateMappedObjectType(type, mapper); + return instantiateAnonymousType(type, mapper); } function isMappableType(type) { return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); + if (type.objectFlags & 32 /* Mapped */) { + result.declaration = type.declaration; + } + result.target = type; + result.mapper = mapper; result.aliasSymbol = type.aliasSymbol; result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); return result; } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - // Starting with the parent of the symbol's declaration, check if the mapper maps any of - // the type parameters introduced by enclosing declarations. We just pick the first - // declaration since multiple declarations will all have the same parent anyway. - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { - return "quit"; - } - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { - var d = typeParameters_1[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172 /* MappedType */: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 273 /* JSDocFunctionType */: - var func = node; - for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { - var p = _b[_a]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; - } - return false; - } function instantiateType(type, mapper) { if (type && mapper !== identityMapper) { - // If we are instantiating a type that has a top-level type alias, obtain the instantiation through - // the type alias instead in order to share instantiations for the same type arguments. This can - // dramatically reduce the number of structurally identical types we generate. Note that we can only - // perform this optimization for top-level type aliases. Consider: - // - // function f1(x: T) { - // type Foo = { x: X, t: T }; - // let obj: Foo = { x: x }; - // return obj; - // } - // function f2(x: U) { return f1(x); } - // let z = f2(42); - // - // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo - // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's - // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been - // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; + } + if (type.objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); + } + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); } - return type; } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. We skip instantiation - // if none of the type parameters that are in scope in the type's declaration are mapped by - // the given mapper, however we can only do that analysis if the type isn't itself an - // instantiation. - return type.symbol && - type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } - if (type.objectFlags & 32 /* Mapped */) { - return instantiateCached(type, mapper, instantiateMappedType); + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); } - if (type.objectFlags & 4 /* Reference */) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } return type; } function instantiateIndexInfo(info, mapper) { @@ -30437,6 +30678,7 @@ var ts; switch (node.kind) { case 186 /* FunctionExpression */: case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); case 178 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); @@ -30450,9 +30692,6 @@ var ts; (isContextSensitive(node.left) || isContextSensitive(node.right)); case 261 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return isContextSensitiveFunctionLikeDeclaration(node); case 185 /* ParenthesizedExpression */: return isContextSensitive(node.expression); case 254 /* JsxAttributes */: @@ -30569,7 +30808,8 @@ var ts; if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return 0 /* False */; } - if (source.typeParameters) { + if (source.typeParameters && source.typeParameters !== target.typeParameters) { + target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var result = -1 /* True */; @@ -30842,7 +31082,14 @@ var ts; var targetStack; var maybeCount = 0; var depth = 0; - var expandingFlags = 0; + var ExpandingFlags; + (function (ExpandingFlags) { + ExpandingFlags[ExpandingFlags["None"] = 0] = "None"; + ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source"; + ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; + ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; + })(ExpandingFlags || (ExpandingFlags = {})); + var expandingFlags = 0 /* None */; var overflow = false; var isIntersectionConstituent = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); @@ -31060,10 +31307,21 @@ var ts; else { // use the property's value declaration if the property is assigned inside the literal itself var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + var suggestion = void 0; if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { - errorNode = prop.valueDeclaration; + var propDeclaration = prop.valueDeclaration; + ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); + errorNode = propDeclaration; + if (ts.isIdentifier(propDeclaration.name)) { + suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + } + } + if (suggestion !== undefined) { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), ts.unescapeLeadingUnderscores(suggestion)); + } + else { + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } return { value: true }; @@ -31229,11 +31487,11 @@ var ts; targetStack[depth] = target; depth++; var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2 /* Target */; + var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -31287,7 +31545,7 @@ var ts; else if (target.flags & 524288 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and // A is the apparent type of S. - var constraint = getConstraintOfType(target); + var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { errorInfo = saveErrorInfo; @@ -31326,7 +31584,7 @@ var ts; else if (source.flags & 524288 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and // A is the apparent type of S. - var constraint = getConstraintOfType(source); + var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { errorInfo = saveErrorInfo; @@ -31414,22 +31672,21 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + if (unmatchedProperty) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + } + return 0 /* False */; + } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 16777216 /* Optional */) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0 /* False */; - } - } - else if (!(targetProp.flags & 4194304 /* Prototype */)) { + if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp && sourceProp !== targetProp) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { @@ -31737,13 +31994,14 @@ var ts; return type.flags & 16384 /* TypeParameter */ && !getConstraintFromTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, isUnconstrainedTypeParameter); + return getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" * where A.id=111 and number.id=12 */ - function getTypeReferenceId(type, typeParameters) { + function getTypeReferenceId(type, typeParameters, depth) { + if (depth === void 0) { depth = 0; } var result = "" + type.target.id; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; @@ -31755,6 +32013,9 @@ var ts; } result += "=" + index; } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; + } else { result += "-" + t.id; } @@ -31958,8 +32219,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -32000,7 +32261,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isUnitType(type) { - return (type.flags & (224 /* Literal */ | 2048 /* Undefined */ | 4096 /* Null */)) !== 0; + return !!(type.flags & 6368 /* Unit */); } function isLiteralType(type) { return type.flags & 8 /* Boolean */ ? true : @@ -32032,8 +32293,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getFalsyFlags(t); } return result; @@ -32276,7 +32537,6 @@ var ts; function createInferenceContext(signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); var context = mapper; - context.mappedTypes = signature.typeParameters; context.signature = signature; context.inferences = inferences; context.flags = flags; @@ -32317,7 +32577,7 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 /* TypeVariable */ || + return !!(type.flags & (540672 /* TypeVariable */ | 262144 /* Index */) || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || @@ -32375,18 +32635,18 @@ var ts; return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); } } - function isPossiblyAssignableTo(source, target) { + function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; - if (!(targetProp.flags & (16777216 /* Optional */ | 4194304 /* Prototype */))) { - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!sourceProp) { - return false; + return targetProp; } } } - return true; + return undefined; } function inferTypes(inferences, originalSource, originalTarget, priority) { if (priority === void 0) { priority = 0; } @@ -32483,6 +32743,13 @@ var ts; inferFromTypes(sourceTypes[i], targetTypes[i]); } } + else if (source.flags & 262144 /* Index */ && target.flags & 262144 /* Index */) { + inferFromTypes(source.type, target.type); + } + else if (source.flags & 524288 /* IndexedAccess */ && target.flags & 524288 /* IndexedAccess */) { + inferFromTypes(source.objectType, target.objectType); + inferFromTypes(source.indexType, target.indexType); + } else if (target.flags & 196608 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -32508,7 +32775,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 196608 /* UnionOrIntersection */) { + else if (source.flags & 65536 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -32518,7 +32785,7 @@ var ts; } else { source = getApparentType(source); - if (source.flags & 32768 /* Object */) { + if (source.flags & (32768 /* Object */ | 131072 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -32557,6 +32824,12 @@ var ts; return undefined; } function inferFromObjectTypes(source, target) { + if (isGenericMappedType(source) && isGenericMappedType(target)) { + // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer + // from S to T and from X to Y. + inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target)); + inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); + } if (getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); if (constraintType.flags & 262144 /* Index */) { @@ -32586,7 +32859,7 @@ var ts; } // Infer from the members of source and target only if the two types are possibly related. We check // in both directions because we may be inferring for a co-variant or a contra-variant position. - if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + if (!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) || !getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -32597,7 +32870,7 @@ var ts; var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + var sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -32643,8 +32916,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -32734,7 +33007,8 @@ var ts; function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { - links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !ts.nodeIsMissing(node) && + resolveName(node, node.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -32915,8 +33189,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getTypeFacts(t); } return result; @@ -33183,8 +33457,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -33264,8 +33538,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -33319,15 +33593,25 @@ var ts; } return false; } + function reportFlowControlError(node) { + var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); + var sourceFile = ts.getSourceFileOfNode(node); + var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); + } function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { if (initialType === void 0) { initialType = declaredType; } var key; + var flowDepth = 0; + if (flowAnalysisDisabled) { + return unknownType; + } if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { return declaredType; } - var visitedFlowStart = visitedFlowCount; + var sharedFlowStart = sharedFlowCount; var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; + sharedFlowCount = sharedFlowStart; // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without @@ -33338,60 +33622,70 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { + if (flowDepth === 2500) { + // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + // and disable further control flow analysis in the containing function or module body. + flowAnalysisDisabled = true; + reportFlowControlError(reference); + return unknownType; + } + flowDepth++; while (true) { - if (flow.flags & 1024 /* Shared */) { + var flags = flow.flags; + if (flags & 1024 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; + for (var i = sharedFlowStart; i < sharedFlowCount; i++) { + if (sharedFlowNodes[i] === flow) { + flowDepth--; + return sharedFlowTypes[i]; } } } var type = void 0; - if (flow.flags & 4096 /* AfterFinally */) { + if (flags & 4096 /* AfterFinally */) { // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement flow.locked = true; type = getTypeAtFlowNode(flow.antecedent); flow.locked = false; } - else if (flow.flags & 2048 /* PreFinally */) { + else if (flags & 2048 /* PreFinally */) { // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel // so here just redirect to antecedent flow = flow.antecedent; continue; } - else if (flow.flags & 16 /* Assignment */) { + else if (flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 96 /* Condition */) { + else if (flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } - else if (flow.flags & 128 /* SwitchClause */) { + else if (flags & 128 /* SwitchClause */) { type = getTypeAtSwitchClause(flow); } - else if (flow.flags & 12 /* Label */) { + else if (flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; continue; } - type = flow.flags & 4 /* BranchLabel */ ? + type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } - else if (flow.flags & 256 /* ArrayMutation */) { + else if (flags & 256 /* ArrayMutation */) { type = getTypeAtFlowArrayMutation(flow); if (!type) { flow = flow.antecedent; continue; } } - else if (flow.flags & 2 /* Start */) { + else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { @@ -33406,12 +33700,13 @@ var ts; // simply return the non-auto declared type to reduce follow-on errors. type = convertAutoToAny(declaredType); } - if (flow.flags & 1024 /* Shared */) { + if (flags & 1024 /* Shared */) { // Record visited node and the associated type in the cache. - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; + sharedFlowNodes[sharedFlowCount] = flow; + sharedFlowTypes[sharedFlowCount] = type; + sharedFlowCount++; } + flowDepth--; return type; } } @@ -33447,30 +33742,32 @@ var ts; return undefined; } function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { - var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + if (declaredType === autoType || declaredType === autoArrayType) { + var node = flow.node; + var expr = node.kind === 181 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 181 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + return flowType; } - return flowType; } return undefined; } @@ -33530,9 +33827,7 @@ var ts; if (type === declaredType && declaredType === initialType) { return type; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); // If an antecedent type is not a subset of the declared type, we need to perform // subtype reduction. This happens when a "foreign" type is injected into the control // flow using the instanceof operator or a user defined type predicate. @@ -33598,9 +33893,7 @@ var ts; if (cached_1) { return cached_1; } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } + ts.pushIfUnique(antecedentTypes, type); // If an antecedent type is not a subset of the declared type, we need to perform // subtype reduction. This happens when a "foreign" type is injected into the control // flow using the instanceof operator or a user defined type predicate. @@ -34571,7 +34864,8 @@ var ts; } } } - if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var inJs = ts.isInJavaScriptFile(func); + if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { // We have an object literal method. Check if the containing object literal has a contextual type @@ -34598,10 +34892,19 @@ var ts; } // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. - if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { - var target = func.parent.left; + var parent = func.parent; + if (parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = parent.left; if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { - return checkExpressionCached(target.expression); + var expression = target.expression; + // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` + if (inJs && ts.isIdentifier(expression)) { + var sourceFile = ts.getSourceFileOfNode(parent); + if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) { + return undefined; + } + } + return checkExpressionCached(expression); } } } @@ -34776,7 +35079,7 @@ var ts; // expression has no contextual type, the right operand is contextually typed by the type of the left operand. var type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); + type = getTypeOfExpression(binaryExpression.left, /*cache*/ true); } return type; } @@ -34834,16 +35137,10 @@ var ts; // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated // type of T. - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1 /* Number */) - || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); - } - return undefined; + function getContextualTypeForElementExpression(arrayContextualType, index) { + return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index) + || getIndexTypeOfContextualType(arrayContextualType, 1 /* Number */) + || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node) { @@ -34948,15 +35245,21 @@ var ts; return getContextualTypeForObjectLiteralElement(parent); case 263 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: - return getContextualTypeForElementExpression(node); + case 177 /* ArrayLiteralExpression */: { + var arrayLiteral = parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); + } case 195 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); case 205 /* TemplateSpan */: ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: - return getContextualType(parent); + case 185 /* ParenthesizedExpression */: { + // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. + var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); + } case 256 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); case 253 /* JsxAttribute */: @@ -35028,8 +35331,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -35072,8 +35375,9 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; + var contextualType = getApparentTypeOfContextualType(node); + for (var index = 0; index < elements.length; index++) { + var e = elements[index]; if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { // Given the following situation: // var c: {}; @@ -35095,7 +35399,8 @@ var ts; } } else { - var type = checkExpressionForMutableLocation(e, checkMode); + var elementContextualType = getContextualTypeForElementExpression(contextualType, index); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; @@ -35108,9 +35413,9 @@ var ts; type.pattern = node; return type; } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; + var contextualType_1 = getApparentTypeOfContextualType(node); + if (contextualType_1 && contextualTypeIsTupleLikeType(contextualType_1)) { + var pattern = contextualType_1.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { @@ -35118,7 +35423,7 @@ var ts; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); + elementTypes.push(contextualType_1.typeArguments[i]); } else { if (patternElement.kind !== 200 /* OmittedExpression */) { @@ -35230,6 +35535,7 @@ var ts; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = memberDecl.symbol; + var literalName = void 0; if (memberDecl.kind === 261 /* PropertyAssignment */ || memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { @@ -35239,6 +35545,12 @@ var ts; } var type = void 0; if (memberDecl.kind === 261 /* PropertyAssignment */) { + if (memberDecl.name.kind === 144 /* ComputedPropertyName */) { + var t = checkComputedPropertyName(memberDecl.name); + if (t.flags & 224 /* Literal */) { + literalName = ts.escapeLeadingUnderscores("" + t.value); + } + } type = checkPropertyAssignment(memberDecl, checkMode); } else if (memberDecl.kind === 151 /* MethodDeclaration */) { @@ -35253,7 +35565,7 @@ var ts; type = jsdocType; } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, member.escapedName); + var prop = createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. @@ -35262,7 +35574,7 @@ var ts; if (isOptional) { prop.flags |= 16777216 /* Optional */; } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; } } @@ -35316,7 +35628,7 @@ var ts; ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (ts.hasDynamicName(memberDecl)) { + if (!literalName && ts.hasDynamicName(memberDecl)) { if (isNumericName(memberDecl.name)) { hasComputedNumberProperty = true; } @@ -35377,7 +35689,8 @@ var ts; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || + return !!(type.flags & (1 /* Any */ | 16777216 /* NonPrimitive */) || + getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || type.flags & 32768 /* Object */ && !isGenericMappedType(type) || type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); } @@ -35622,8 +35935,9 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + var isJavascript = ts.isInJavaScriptFile(node); + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0, isJavascript); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } else { instantiatedSignatures.push(signature); @@ -36016,7 +36330,7 @@ var ts; // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -36264,19 +36578,8 @@ var ts; } return unknownType; } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); - } - } - markPropertyAsReferenced(prop); + checkPropertyNotUsedBeforeDeclaration(prop, node, right); + markPropertyAsReferenced(prop, node); getNodeLinks(node).resolvedSymbol = prop; checkPropertyAccessibility(node, left, apparentType, prop); var propType = getDeclaredOrApparentType(prop, node); @@ -36298,6 +36601,61 @@ var ts; var flowType = getFlowTypeOfReference(node, propType); return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function checkPropertyNotUsedBeforeDeclaration(prop, node, right) { + var valueDeclaration = prop.valueDeclaration; + if (!valueDeclaration) { + return; + } + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) + && !isPropertyDeclaredInAncestorClass(prop)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + else if (valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + function isInPropertyInitializer(node) { + return !!ts.findAncestor(node, function (node) { + switch (node.kind) { + case 149 /* PropertyDeclaration */: + return true; + case 261 /* PropertyAssignment */: + // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + return false; + default: + return ts.isPartOfExpression(node) ? false : "quit"; + } + }); + } + /** + * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass. + * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration. + */ + function isPropertyDeclaredInAncestorClass(prop) { + var classType = getTypeOfSymbol(prop.parent); + while (true) { + classType = getSuperClass(classType); + if (!classType) { + return false; + } + var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + if (superProperty && superProperty.valueDeclaration) { + return true; + } + } + } + function getSuperClass(classType) { + var x = getBaseTypes(classType); + if (x.length === 0) { + return undefined; + } + ts.Debug.assert(x.length === 1); + return x[0]; + } function reportNonexistentProperty(propNode, containingType) { var errorInfo; if (containingType.flags & 65536 /* Union */ && !(containingType.flags & 8190 /* Primitive */)) { @@ -36310,8 +36668,8 @@ var ts; } } var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + if (suggestion !== undefined) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), ts.unescapeLeadingUnderscores(suggestion)); } else { errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); @@ -36323,7 +36681,7 @@ var ts; return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location, name, meaning) { - var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, function (symbols, name, meaning) { + var result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ false, function (symbols, name, meaning) { var symbol = getSymbol(symbols, name, meaning); if (symbol) { // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -36402,11 +36760,12 @@ var ts; } return bestCandidate; } - function markPropertyAsReferenced(prop) { + function markPropertyAsReferenced(prop, nodeForCheckWriteOnly) { if (prop && noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && - prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 8 /* Private */) + && !(nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly))) { if (ts.getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } @@ -36415,15 +36774,6 @@ var ts; } } } - function isInPropertyInitializer(node) { - while (node) { - if (node.parent && node.parent.kind === 149 /* PropertyDeclaration */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } function isValidPropertyAccess(node, propertyName) { var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression @@ -36648,7 +36998,6 @@ var ts; var argCount; // Apparent number of arguments we will have in this call var typeArguments; // Type arguments (undefined if none) var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments - var isDecorator; var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -36678,7 +37027,6 @@ var ts; } } else if (node.kind === 147 /* Decorator */) { - isDecorator = true; typeArguments = undefined; argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } @@ -36738,7 +37086,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } function inferTypeArguments(node, signature, args, excludeArgument, context) { // Clear out all the inference results from the last time inferTypeArguments was called on this context @@ -36756,7 +37104,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (ts.isExpression(node)) { + if (node.kind !== 147 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -36772,7 +37120,7 @@ var ts; // Above, the type of the 'value' parameter is inferred to be 'A'. var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. @@ -37415,8 +37763,9 @@ var ts; candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; + var isJavascript = ts.isInJavaScriptFile(candidate.declaration); if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters), isJavascript); if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { candidateForTypeArgumentError = originalCandidate; break; @@ -37425,7 +37774,7 @@ var ts; else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -37559,15 +37908,6 @@ var ts; // Another error has already been reported return resolveErrorCall(node); } - // If the expression is a class of abstract type, then it cannot be instantiated. - // Note, only class declarations can be declared abstract. - // In the case of a merged class-module or class-interface declaration, - // only the class declaration node will have the Abstract flag set. - var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } // TS 1.0 spec: 4.11 // If expressionType is of type Any, Args can be any argument // list and the result of the operation is of type Any. @@ -37586,6 +37926,15 @@ var ts; if (!isConstructorAccessible(node, constructSignatures[0])) { return resolveErrorCall(node); } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } return resolveCall(node, constructSignatures, candidatesOutArray); } // If expressionType's apparent type is an object type with no construct signatures but @@ -37732,8 +38081,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var type = types_17[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -37759,7 +38108,7 @@ var ts; // This code-path is called by language service return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -37791,18 +38140,32 @@ var ts; * file. */ function isJavaScriptConstructor(node) { - if (ts.isInJavaScriptFile(node)) { + if (node && ts.isInJavaScriptFile(node)) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; return symbol && symbol.members !== undefined; } return false; } + function getJavaScriptClassType(symbol) { + if (ts.isDeclarationOfFunctionOrClassExpression(symbol)) { + symbol = getSymbolOfNode(symbol.valueDeclaration.initializer); + } + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + return getInferredClassType(symbol); + } + if (symbol.flags & 3 /* Variable */) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType) && isJavaScriptConstructor(valueType.symbol.valueDeclaration)) { + return getInferredClassType(valueType.symbol); + } + } + } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); if (!links.inferredClassType) { @@ -37842,13 +38205,11 @@ var ts; var funcSymbol = node.expression.kind === 71 /* Identifier */ ? getResolvedSymbol(node.expression) : checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.flags & 16 /* Function */ && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { - return getInferredClassType(funcSymbol); + var type = funcSymbol && getJavaScriptClassType(funcSymbol); + if (type) { + return type; } - else if (noImplicitAny) { + if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; @@ -37914,7 +38275,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) throw ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -38022,8 +38383,9 @@ var ts; } } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.lastOrUndefined(signature.parameters); - if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } @@ -38169,9 +38531,7 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } }); return aggregatedTypes; @@ -38219,9 +38579,7 @@ var ts; if (type.flags & 8192 /* Never */) { hasReturnOfTypeNever = true; } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } + ts.pushIfUnique(aggregatedTypes, type); } else { hasReturnWithNoExpression = true; @@ -38232,9 +38590,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } + ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } @@ -38539,8 +38895,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -39097,20 +39453,6 @@ var ts; var type2 = checkExpression(node.whenFalse, checkMode); return getBestChoiceType(type1, type2); } - function checkLiteralExpression(node) { - switch (node.kind) { - case 13 /* NoSubstitutionTemplateLiteral */: - case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8 /* NumericLiteral */: - checkGrammarNumericLiteral(node); - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: - return trueType; - case 86 /* FalseKeyword */: - return falseType; - } - } function checkTemplateExpression(node) { // We just want to check each expressions, but we are unconcerned with // the type of each expression, as any value may be coerced into a string. @@ -39173,9 +39515,13 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode) { + function checkExpressionForMutableLocation(node, checkMode, contextualType) { + if (arguments.length === 2) { + contextualType = getContextualType(node); + } var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + var shouldWiden = isTypeAssertion(node) || isLiteralContextualType(contextualType); + return shouldWiden ? type : getWidenedLiteralType(type); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -39279,13 +39625,9 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281 /* JSDocTypeTag */; }); }); - if (typecasts && typecasts.length) { - // We should have already issued an error if there were multiple type jsdocs - var cast_1 = typecasts[0]; - return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); - } + var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + if (tag) { + return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } @@ -39301,10 +39643,14 @@ var ts; return nullWideningType; case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); case 8 /* NumericLiteral */: + checkGrammarNumericLiteral(node); + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); case 101 /* TrueKeyword */: + return trueType; case 86 /* FalseKeyword */: - return checkLiteralExpression(node); + return falseType; case 196 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: @@ -39920,7 +40266,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, ts.isInJavaScriptFile(typeArgumentNodes[i])); mapper = createTypeMapper(typeParameters, typeArguments); } var typeArgument = typeArguments[i]; @@ -39994,6 +40340,10 @@ var ts; var objectType = type.objectType; var indexType = type.indexType; if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + if (accessNode.kind === 180 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + getObjectFlags(objectType) & 32 /* Mapped */ && objectType.declaration.readonlyToken) { + error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + } return type; } // Check if we're indexing with a numeric type and if either object or index types @@ -40296,6 +40646,8 @@ var ts; switch (d.kind) { case 230 /* InterfaceDeclaration */: case 231 /* TypeAliasDeclaration */: + // A jsdoc typedef is, by definition, a type alias + case 283 /* JSDocTypedefTag */: return 2 /* ExportType */; case 233 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -40304,7 +40656,10 @@ var ts; case 229 /* ClassDeclaration */: case 232 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; + // The below options all declare an Alias, which is allowed to merge with other values within the importing module case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 239 /* ImportClause */: var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); @@ -40613,8 +40968,11 @@ var ts; markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); } function markEntityNameOrEntityExpressionAsReference(typeName) { - var rootName = typeName && getFirstIdentifier(typeName); - var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!typeName) + return; + var rootName = getFirstIdentifier(typeName); + var meaning = (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ && symbolIsValue(rootSymbol) @@ -40738,22 +41096,13 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDoc(node) { - if (!ts.isInJavaScriptFile(node)) { - return; - } - ts.forEach(node.jsDoc, checkSourceElement); - } - function checkJSDocComment(node) { - if (node.tags) { - for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { - var tag = _a[_i]; - checkSourceElement(tag); - } + function checkJSDocTypedefTag(node) { + if (!node.typeExpression) { + // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. + error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } } function checkFunctionOrMethodDeclaration(node) { - checkJSDoc(node); checkDecorators(node); checkSignatureDeclaration(node); var functionFlags = ts.getFunctionFlags(node); @@ -40879,11 +41228,11 @@ var ts; !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.unescapeLeadingUnderscores(local.escapedName)); }); } } }); @@ -40896,15 +41245,17 @@ var ts; } return false; } - function errorUnusedLocal(node, name) { + function errorUnusedLocal(declaration, name) { + var node = ts.getNameOfDeclaration(declaration) || declaration; if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration.parent.parent)) { + var declaration_2 = ts.getRootDeclaration(node.parent); + if ((declaration_2.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || + declaration_2.kind === 145 /* TypeParameter */) { return; } } if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + error(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name); } } function parameterNameStartsWithUnderscore(parameterName) { @@ -40920,14 +41271,14 @@ var ts; var member = _a[_i]; if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === 152 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -40947,8 +41298,8 @@ var ts; } for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + if (!getMergedSymbol(typeParameter.symbol).isReferenced && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -40961,7 +41312,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + errorUnusedLocal(declaration, ts.unescapeLeadingUnderscores(local.escapedName)); } } } @@ -40973,7 +41324,14 @@ var ts; if (node.kind === 207 /* Block */) { checkGrammarStatementInAmbientContext(node); } - ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionOrModuleBlock(node)) { + var saveFlowAnalysisDisabled = flowAnalysisDisabled; + ts.forEach(node.statements, checkSourceElement); + flowAnalysisDisabled = saveFlowAnalysisDisabled; + } + else { + ts.forEach(node.statements, checkSourceElement); + } if (node.locals) { registerForUnusedIdentifiersCheck(node); } @@ -41143,7 +41501,7 @@ var ts; if (symbol.flags & 1 /* FunctionScopedVariable */) { if (!ts.isIdentifier(node.name)) throw ts.Debug.fail(); - var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { @@ -41191,7 +41549,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -41268,7 +41626,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); + markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); } @@ -42955,9 +43313,9 @@ var ts; } } else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + if (modulekind >= ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above - grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } } } @@ -42988,7 +43346,7 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); } } @@ -43007,7 +43365,7 @@ var ts; var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); } @@ -43042,10 +43400,13 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); + if (ts.isInAmbientContext(node) && !ts.isEntityNameExpression(node.expression)) { + grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); + } if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { + if (modulekind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (modulekind === ts.ModuleKind.System) { // system modules does not support export assignment @@ -43079,7 +43440,7 @@ var ts; if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { return; } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor); if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { // it is legal to merge type alias with other values // so count should be either 1 (just type alias) or 2 (type alias + merged value) @@ -43096,15 +43457,25 @@ var ts; }); links.exportsChecked = true; } - function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || - !!declaration.body; - } + } + function isNotAccessor(declaration) { + // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks + return !ts.isAccessor(declaration); + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var tags = _a[_i].tags; + ts.forEach(tags, checkSourceElement); + } + } var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively @@ -43158,8 +43529,8 @@ var ts; case 168 /* ParenthesizedType */: case 170 /* TypeOperator */: return checkSourceElement(node.type); - case 275 /* JSDocComment */: - return checkJSDocComment(node); + case 283 /* JSDocTypedefTag */: + return checkJSDocTypedefTag(node); case 279 /* JSDocParameterTag */: return checkSourceElement(node.typeExpression); case 273 /* JSDocFunctionType */: @@ -43304,6 +43675,7 @@ var ts; ts.clear(potentialNewTargetCollisions); deferredNodes = []; deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + flowAnalysisDisabled = false; ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalModule(node)) { @@ -43674,12 +44046,14 @@ var ts; return sig.thisParameter; } } + if (ts.isInExpressionContext(node)) { + return checkExpression(node).symbol; + } // falls through - case 97 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; case 169 /* ThisType */: - return getTypeFromTypeNode(node).symbol; + return getTypeFromThisTypeNode(node).symbol; + case 97 /* SuperKeyword */: + return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; @@ -43699,13 +44073,17 @@ var ts; // falls through case 8 /* NumericLiteral */: // index access - if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - return getPropertyOfType(objectType, node.text); - } - break; + var objectType = ts.isElementAccessExpression(node.parent) + ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined + : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) + ? getTypeFromTypeNode(node.parent.parent.objectType) + : undefined; + return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); + case 79 /* DefaultKeyword */: + return getSymbolOfNode(node.parent); + default: + return undefined; } - return undefined; } function getShorthandAssignmentValueSymbol(location) { // The function returns a value symbol of an identifier in the short-hand property assignment. @@ -43853,9 +44231,9 @@ var ts; function getRootSymbols(symbol) { if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { var symbols_4 = []; - var name_2 = symbol.escapedName; + var name_3 = symbol.escapedName; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_2); + var symbol = getPropertyOfType(t, name_3); if (symbol) { symbols_4.push(symbol); } @@ -43976,7 +44354,7 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + if (resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -44155,6 +44533,15 @@ var ts; return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; } function getTypeReferenceSerializationKind(typeName, location) { + // ensure both `typeName` and `location` are parse tree nodes. + typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + if (!typeName) + return ts.TypeReferenceSerializationKind.Unknown; + if (location) { + location = ts.getParseTreeNode(location); + if (!location) + return ts.TypeReferenceSerializationKind.Unknown; + } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. @@ -44244,7 +44631,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(reference) { if (!ts.isGeneratedIdentifier(reference)) { @@ -44547,7 +44934,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var lastStatic, lastDeclare, lastAsync, lastReadonly; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -44569,12 +44956,6 @@ var ts; case 113 /* ProtectedKeyword */: case 112 /* PrivateKeyword */: var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113 /* ProtectedKeyword */) { - lastProtected = modifier; - } - else if (modifier.kind === 112 /* PrivateKeyword */) { - lastPrivate = modifier; - } if (flags & 28 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } @@ -45089,7 +45470,7 @@ var ts; currentKind = SetAccessor; } else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -45372,7 +45753,7 @@ var ts; } } } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } @@ -45393,8 +45774,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; if (!ts.isOmittedExpression(element)) { return checkESModuleMarker(element.name); } @@ -45409,8 +45790,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -45908,7 +46289,7 @@ var ts; || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node) + ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node) : node; } ts.updateParameter = updateParameter; @@ -46531,13 +46912,26 @@ var ts; return node; } ts.createArrowFunction = createArrowFunction; - function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) { + function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanTokenOrBody, bodyOrUndefined) { + var equalsGreaterThanToken; + var body; + if (bodyOrUndefined === undefined) { + equalsGreaterThanToken = node.equalsGreaterThanToken; + body = ts.cast(equalsGreaterThanTokenOrBody, ts.isConciseBody); + } + else { + equalsGreaterThanToken = ts.cast(equalsGreaterThanTokenOrBody, function (n) { + return n.kind === 36 /* EqualsGreaterThanToken */; + }); + body = bodyOrUndefined; + } return node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type + || node.equalsGreaterThanToken !== equalsGreaterThanToken || node.body !== body - ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node) + ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) : node; } ts.updateArrowFunction = updateArrowFunction; @@ -46642,11 +47036,23 @@ var ts; return node; } ts.createConditional = createConditional; - function updateConditional(node, condition, whenTrue, whenFalse) { + function updateConditional(node, condition) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (args.length === 2) { + var whenTrue_1 = args[0], whenFalse_1 = args[1]; + return updateConditional(node, condition, node.questionToken, whenTrue_1, node.colonToken, whenFalse_1); + } + ts.Debug.assert(args.length === 4); + var questionToken = args[0], whenTrue = args[1], colonToken = args[2], whenFalse = args[3]; return node.condition !== condition + || node.questionToken !== questionToken || node.whenTrue !== whenTrue + || node.colonToken !== colonToken || node.whenFalse !== whenFalse - ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node) + ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node) : node; } ts.updateConditional = updateConditional; @@ -46664,6 +47070,30 @@ var ts; : node; } ts.updateTemplateExpression = updateTemplateExpression; + function createTemplateHead(text) { + var node = createSynthesizedNode(14 /* TemplateHead */); + node.text = text; + return node; + } + ts.createTemplateHead = createTemplateHead; + function createTemplateMiddle(text) { + var node = createSynthesizedNode(15 /* TemplateMiddle */); + node.text = text; + return node; + } + ts.createTemplateMiddle = createTemplateMiddle; + function createTemplateTail(text) { + var node = createSynthesizedNode(16 /* TemplateTail */); + node.text = text; + return node; + } + ts.createTemplateTail = createTemplateTail; + function createNoSubstitutionTemplateLiteral(text) { + var node = createSynthesizedNode(13 /* NoSubstitutionTemplateLiteral */); + node.text = text; + return node; + } + ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { var node = createSynthesizedNode(197 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; @@ -47795,6 +48225,17 @@ var ts; /*argumentsArray*/ paramValue ? [paramValue] : []); } ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedArrowFunction(statements, param, paramValue) { + return createCall(createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction; function createComma(left, right) { return createBinary(left, 26 /* CommaToken */, right); } @@ -48044,9 +48485,7 @@ var ts; var emitNode = getOrCreateEmitNode(node); for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) { var helper = helpers_1[_i]; - if (!ts.contains(emitNode.helpers, helper)) { - emitNode.helpers = ts.append(emitNode.helpers, helper); - } + emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper); } } return node; @@ -48088,9 +48527,7 @@ var ts; var helper = sourceEmitHelpers[i]; if (predicate(helper)) { helpersRemoved++; - if (!ts.contains(targetEmitNode.helpers, helper)) { - targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper); - } + targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper); } else if (helpersRemoved > 0) { sourceEmitHelpers[i - helpersRemoved] = helper; @@ -49055,11 +49492,9 @@ var ts; return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } - else { - var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; - if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { - return ts.setTextRange(ts.createParen(expression), expression); - } + var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind; + if (leftmostExpressionKind === 178 /* ObjectLiteralExpression */ || leftmostExpressionKind === 186 /* FunctionExpression */) { + return ts.setTextRange(ts.createParen(expression), expression); } return expression; } @@ -49195,9 +49630,31 @@ var ts; case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } + /** + * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions. + * + * A parenthesized expression can be ignored when all of the following are true: + * + * - It's `pos` and `end` are not -1 + * - It does not have a custom source map range + * - It does not have a custom comment range + * - It does not have synthetic leading or trailing comments + * + * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around + * the expression to maintain precedence, a new parenthesized expression should be created automatically when + * the containing expression is created/updated. + */ + function isIgnorableParen(node) { + return node.kind === 185 /* ParenthesizedExpression */ + && ts.nodeIsSynthesized(node) + && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) + && ts.nodeIsSynthesized(ts.getCommentRange(node)) + && !ts.some(ts.getSyntheticLeadingComments(node)) + && !ts.some(ts.getSyntheticTrailingComments(node)); + } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } - if (outerExpression && isOuterExpression(outerExpression, kinds)) { + if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } return innerExpression; @@ -49223,7 +49680,8 @@ var ts; var moduleKind = ts.getEmitModuleKind(compilerOptions); var create = hasExportStarsToExportValues && moduleKind !== ts.ModuleKind.System - && moduleKind !== ts.ModuleKind.ES2015; + && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext; if (!create) { var helpers = ts.getEmitHelpers(node); if (helpers) { @@ -49793,7 +50251,7 @@ var ts; case 186 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187 /* ArrowFunction */: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 188 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189 /* TypeOfExpression */: @@ -49809,7 +50267,7 @@ var ts; case 194 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); case 195 /* ConditionalExpression */: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 196 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 197 /* YieldExpression */: @@ -50649,7 +51107,7 @@ var ts; else { // export class x { } var name = node.name; - if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + if (name && !uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); exportedNames = ts.append(exportedNames, name); @@ -51047,7 +51505,7 @@ var ts; */ function createDestructuringPropertyAccess(flattenContext, value, propertyName) { if (ts.isComputedPropertyName(propertyName)) { - var argumentExpression = ensureIdentifier(flattenContext, propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); + var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); return ts.createElementAccess(value, argumentExpression); } else if (ts.isStringOrNumericLiteral(propertyName)) { @@ -51316,6 +51774,23 @@ var ts; * @param node The node to visit. */ function sourceElementVisitorWorker(node) { + switch (node.kind) { + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 243 /* ExportAssignment */: + case 244 /* ExportDeclaration */: + return visitEllidableStatement(node); + default: + return visitorWorker(node); + } + } + function visitEllidableStatement(node) { + var parsed = ts.getParseTreeNode(node); + if (parsed !== node) { + // If the node has been transformed by a `before` transformer, perform no ellision on it + // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes + return node; + } switch (node.kind) { case 238 /* ImportDeclaration */: return visitImportDeclaration(node); @@ -51326,7 +51801,7 @@ var ts; case 244 /* ExportDeclaration */: return visitExportDeclaration(node); default: - return visitorWorker(node); + ts.Debug.fail("Unhandled ellided statement"); } } /** @@ -51567,7 +52042,7 @@ var ts; } function visitSourceFile(node) { var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) && - !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -51667,10 +52142,12 @@ var ts; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, context.endLexicalEnvironment()); + var iife = ts.createImmediatelyInvokedArrowFunction(statements); + ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), - /*type*/ undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + /*type*/ undefined, iife) ])); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); @@ -52773,7 +53250,7 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8 /* Synthesized */; name.original = undefined; - name.parent = currentScope; + name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. if (useFallback) { return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); } @@ -53028,7 +53505,7 @@ var ts; function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context)); + /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } /** @@ -53278,6 +53755,7 @@ var ts; return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 + && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System); } /** @@ -53983,8 +54461,6 @@ var ts; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - // These variables contain state that changes as we descend into the tree. - var currentSourceFile; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. * They are persisted between each SourceFile transformation and should not be reset. @@ -54006,10 +54482,8 @@ var ts; if (node.isDeclarationFile) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } function visitor(node) { @@ -54104,7 +54578,7 @@ var ts; function visitArrowFunction(node) { return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */ + /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */ ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } @@ -54435,8 +54909,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { - var e = elements_4[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var e = elements_3[_i]; if (e.kind === 263 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -54454,7 +54928,7 @@ var ts; chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression))); } else { - chunkObject.push(e); + chunkObject.push(ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } } } @@ -54693,7 +55167,7 @@ var ts; enclosingFunctionFlags = ts.getFunctionFlags(node); var updated = ts.updateArrowFunction(node, node.modifiers, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), - /*type*/ undefined, transformFunctionBody(node)); + /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; return updated; } @@ -55689,58 +56163,12 @@ var ts; && node.kind === 219 /* ReturnStatement */ && !node.expression; } - function isClassLikeVariableStatement(node) { - if (!ts.isVariableStatement(node)) - return false; - var variable = ts.singleOrUndefined(node.declarationList.declarations); - return variable - && variable.initializer - && ts.isIdentifier(variable.name) - && (ts.isClassLike(variable.initializer) - || (ts.isAssignmentExpression(variable.initializer) - && ts.isIdentifier(variable.initializer.left) - && ts.isClassLike(variable.initializer.right))); - } - function isTypeScriptClassWrapper(node) { - var call = ts.tryCast(node, ts.isCallExpression); - if (!call || ts.isParseTreeNode(call) || - ts.some(call.typeArguments) || - ts.some(call.arguments)) { - return false; - } - var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); - if (!func || ts.isParseTreeNode(func) || - ts.some(func.typeParameters) || - ts.some(func.parameters) || - func.type || - !func.body) { - return false; - } - var statements = func.body.statements; - if (statements.length < 2) { - return false; - } - var firstStatement = statements[0]; - if (ts.isParseTreeNode(firstStatement) || - !ts.isClassLike(firstStatement) && - !isClassLikeVariableStatement(firstStatement)) { - return false; - } - var lastStatement = ts.elementAt(statements, -1); - var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); - if (!returnStatement || - !returnStatement.expression || - !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { - return false; - } - return true; - } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 207 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) - || isTypeScriptClassWrapper(node); + || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { if (shouldVisitNode(node)) { @@ -57875,7 +58303,7 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { - if (isTypeScriptClassWrapper(node)) { + if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } if (node.transformFlags & 64 /* ES2015 */) { @@ -57917,7 +58345,7 @@ var ts; // }()) // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. - var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); // The class statements are the statements generated by visiting the first statement of the // body (1), while all other statements are added to remainingStatements (2) var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); @@ -58820,7 +59248,6 @@ var ts; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - var currentSourceFile; var renamedCatchVariables; var renamedCatchVariableDeclarations; var inGeneratorFunctionBody; @@ -58867,10 +59294,8 @@ var ts; if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; } - currentSourceFile = node; var visited = ts.visitEachChild(node, visitor, context); ts.addEmitHelpers(visited, context.readEmitHelpers()); - currentSourceFile = undefined; return visited; } /** @@ -61437,6 +61862,7 @@ var ts; */ function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; + var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var umdHeader = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -61456,13 +61882,13 @@ var ts; ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ ts.createStatement(ts.createCall(ts.createIdentifier("define"), - /*typeArguments*/ undefined, [ + /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), ts.createIdentifier("factory") - ])) + ]))) ]))) ], /*multiLine*/ true), @@ -61588,17 +62014,20 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - if (emitAsReturn) { - var statement = ts.createReturn(currentModuleInfo.exportEquals.expression); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); - statements.push(statement); - } - else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression)); - ts.setTextRange(statement, currentModuleInfo.exportEquals); - ts.setEmitFlags(statement, 1536 /* NoComments */); - statements.push(statement); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + if (expressionResult) { + if (emitAsReturn) { + var statement = ts.createReturn(expressionResult); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + statements.push(statement); + } + else { + var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + ts.setTextRange(statement, currentModuleInfo.exportEquals); + ts.setEmitFlags(statement, 1536 /* NoComments */); + statements.push(statement); + } } } } @@ -62143,7 +62572,7 @@ var ts; return statements; } if (ts.hasModifier(decl, 1 /* Export */)) { - var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name; + var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl); statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl); } if (decl.name) { @@ -63352,7 +63781,8 @@ var ts; */ function createExportExpression(name, value) { var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name; - return ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]); + ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */); + return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value); } // // Top-Level or Nested Source Element Visitors @@ -67105,8 +67535,15 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } + // TODO: Should this just be `emit`? + // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 + function emitIfPresent(node) { + if (node) { + emit(node); + } + } function emit(node) { - pipelineEmitWithNotification(3 /* Unspecified */, node); + pipelineEmitWithNotification(4 /* Unspecified */, node); } function emitIdentifierName(node) { pipelineEmitWithNotification(2 /* IdentifierName */, node); @@ -67144,7 +67581,8 @@ var ts; case 0 /* SourceFile */: return pipelineEmitSourceFile(node); case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* Unspecified */: return pipelineEmitUnspecified(node); + case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + case 4 /* Unspecified */: return pipelineEmitUnspecified(node); } } function pipelineEmitSourceFile(node) { @@ -67155,6 +67593,11 @@ var ts; ts.Debug.assertNode(node, ts.isIdentifier); emitIdentifier(node); } + function emitMappedTypeParameter(node) { + emit(node.name); + write(" in "); + emit(node.constraint); + } function pipelineEmitUnspecified(node) { var kind = node.kind; // Reserved words @@ -67544,9 +67987,9 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } @@ -67561,7 +68004,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); write(";"); } @@ -67569,7 +68012,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -67578,7 +68021,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitWithPrefix(": ", node.type); @@ -67587,9 +68030,9 @@ var ts; function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeIfPresent(node.asteriskToken, "*"); + emitIfPresent(node.asteriskToken); emit(node.name); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -67662,10 +68105,8 @@ var ts; } function emitTypeLiteral(node) { write("{"); - // If the literal is empty, do not add spaces between braces. - if (node.members.length > 0) { - emitList(node, node.members, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */); - } + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); write("}"); } function emitArrayType(node) { @@ -67712,13 +68153,14 @@ var ts; writeLine(); increaseIndent(); } - writeIfPresent(node.readonlyToken, "readonly "); + if (node.readonlyToken) { + emit(node.readonlyToken); + write(" "); + } write("["); - emit(node.typeParameter.name); - write(" in "); - emit(node.typeParameter.constraint); + pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); write("]"); - writeIfPresent(node.questionToken, "?"); + emitIfPresent(node.questionToken); write(": "); emit(node.type); write(";"); @@ -67761,7 +68203,7 @@ var ts; } function emitBindingElement(node) { emitWithSuffix(node.propertyName, ": "); - writeIfPresent(node.dotDotDotToken, "..."); + emitIfPresent(node.dotDotDotToken); emit(node.name); emitExpressionWithPrefix(" = ", node.initializer); } @@ -67770,30 +68212,19 @@ var ts; // function emitArrayLiteralExpression(node) { var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else { - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); - } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { - var properties = node.properties; - if (properties.length === 0) { - write("{}"); + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; + if (indentedFlag) { + increaseIndent(); } - else { - var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; - if (indentedFlag) { - increaseIndent(); - } - var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; - emitList(node, properties, 978 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); - if (indentedFlag) { - decreaseIndent(); - } + var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); + if (indentedFlag) { + decreaseIndent(); } } function emitPropertyAccessExpression(node) { @@ -67880,7 +68311,8 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); emitWithPrefix(": ", node.type); - write(" =>"); + write(" "); + emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { write("delete "); @@ -67947,12 +68379,12 @@ var ts; var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); emitExpression(node.condition); increaseIndentIf(indentBeforeQuestion, " "); - write("?"); + emit(node.questionToken); increaseIndentIf(indentAfterQuestion, " "); emitExpression(node.whenTrue); decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); increaseIndentIf(indentBeforeColon, " "); - write(":"); + emit(node.colonToken); increaseIndentIf(indentAfterColon, " "); emitExpression(node.whenFalse); decreaseIndentIf(indentBeforeColon, indentAfterColon); @@ -67962,7 +68394,8 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write(node.asteriskToken ? "yield*" : "yield"); + write("yield"); + emit(node.asteriskToken); emitExpressionWithPrefix(" ", node.expression); } function emitSpreadExpression(node) { @@ -68003,28 +68436,17 @@ var ts; // Statements // function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); - write(" "); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); - } - else { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); - emitBlockStatements(node); - // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted - increaseIndent(); - emitLeadingCommentsOfPosition(node.statements.end); - decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); - } + writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); + // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); + writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } - function emitBlockStatements(node) { - if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - emitList(node, node.statements, 384 /* SingleLineBlockStatements */); - } - else { - emitList(node, node.statements, 65 /* MultiLineBlockStatements */); - } + function emitBlockStatements(node, forceSingleLine) { + var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; + emitList(node, node.statements, format); } function emitVariableStatement(node) { emitModifiers(node, node.modifiers); @@ -68205,7 +68627,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.asteriskToken ? "function* " : "function "); + write("function"); + emitIfPresent(node.asteriskToken); + write(" "); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -68223,7 +68647,7 @@ var ts; if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3 /* Unspecified */, body, emitBlockCallback); + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -68233,7 +68657,7 @@ var ts; pushNameGenerationScope(); emitSignatureHead(node); if (onEmitNode) { - onEmitNode(3 /* Unspecified */, body, emitBlockCallback); + onEmitNode(4 /* Unspecified */, body, emitBlockCallback); } else { emitBlockFunctionBody(body); @@ -68378,7 +68802,9 @@ var ts; } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + if (~node.flags & 512 /* GlobalAugmentation */) { + write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + } emit(node.name); var body = node.body; while (body.kind === 233 /* ModuleDeclaration */) { @@ -68390,16 +68816,11 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isEmptyBlock(node)) { - write("{ }"); - } - else { - pushNameGenerationScope(); - write("{"); - emitBlockStatements(node); - write("}"); - popNameGenerationScope(); - } + pushNameGenerationScope(); + write("{"); + emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); + write("}"); + popNameGenerationScope(); } function emitCaseBlock(node) { writeToken(17 /* OpenBraceToken */, node.pos); @@ -68550,9 +68971,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { write("{"); - if (node.dotDotDotToken) { - write("..."); - } + emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); write("}"); } @@ -68600,13 +69019,12 @@ var ts; // Note: we can't use parentNode.end as such position includes statements. emitTrailingCommentsOfPosition(statements.pos); } + var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { write(" "); - emit(statements[0]); - } - else { - emitList(parentNode, statements, 81985 /* CaseOrDefaultClauseStatements */); + format &= ~(1 /* MultiLine */ | 64 /* Indented */); } + emitList(parentNode, statements, format); } function emitHeritageClause(node) { write(" "); @@ -68827,7 +69245,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emit(parameters[0]); + emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -68849,8 +69267,14 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || children.length === 0 || start >= children.length || count === 0; + var isEmpty = isUndefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { + if (onBeforeEmitNodeArray) { + onBeforeEmitNodeArray(children); + } + if (onAfterEmitNodeArray) { + onAfterEmitNodeArray(children); + } return; } if (format & 7680 /* BracketsMask */) { @@ -68864,7 +69288,7 @@ var ts; if (format & 1 /* MultiLine */) { writeLine(); } - else if (format & 128 /* SpaceBetweenBraces */) { + else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { write(" "); } } @@ -68944,7 +69368,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -68983,11 +69407,6 @@ var ts; write(text); } } - function writeIfPresent(node, text) { - if (node) { - write(text); - } - } function writeToken(token, pos, contextNode) { return onEmitSourceMapOfToken ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) @@ -68997,7 +69416,7 @@ var ts; if (onBeforeEmitToken) { onBeforeEmitToken(node); } - writeTokenText(node.kind); + write(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } @@ -69151,10 +69570,6 @@ var ts; && !ts.nodeIsSynthesized(node2) && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); } - function isSingleLineEmptyBlock(block) { - return !block.multiLine - && isEmptyBlock(block); - } function isEmptyBlock(block) { return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); @@ -69463,6 +69878,8 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; + ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty"; + ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; @@ -69473,7 +69890,7 @@ var ts; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; - ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; + ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements"; ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments"; @@ -69680,7 +70097,7 @@ var ts; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (program.getCompilerOptions().declaration) { - diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -69704,7 +70121,7 @@ var ts; var redForegroundEscapeSequence = "\u001b[91m"; var yellowForegroundEscapeSequence = "\u001b[93m"; var blueForegroundEscapeSequence = "\u001b[93m"; - var gutterStyleSequence = "\u001b[100;30m"; + var gutterStyleSequence = "\u001b[30;47m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -69729,9 +70146,9 @@ var ts; for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; if (diagnostic.file) { - var start = diagnostic.start, length_6 = diagnostic.length, file = diagnostic.file; + var start = diagnostic.start, length_5 = diagnostic.length, file = diagnostic.file; var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_6), lastLine = _b.line, lastLineChar = _b.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_5), lastLine = _b.line, lastLineChar = _b.character; var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -69739,12 +70156,12 @@ var ts; if (hasMoreThanFiveLines) { gutterWidth = Math.max(ellipsis.length, gutterWidth); } - output += ts.sys.newLine; + output += host.getNewLine(); for (var i = firstLine; i <= lastLine; i++) { // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -69754,7 +70171,7 @@ var ts; lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - output += lineContent + ts.sys.newLine; + output += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; output += redForegroundEscapeSequence; @@ -69773,15 +70190,15 @@ var ts; output += lineContent.replace(/./g, "~"); } output += resetEscapeSequence; - output += ts.sys.newLine; + output += host.getNewLine(); } - output += ts.sys.newLine; + output += host.getNewLine(); output += relativeFileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } var categoryColor = getCategoryFormat(diagnostic.category); var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); - output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); - output += ts.sys.newLine; + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + output += host.getNewLine(); } return output; } @@ -69870,6 +70287,8 @@ var ts; ts.performance.mark("beforeProgram"); host = host || createCompilerHost(options); var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); @@ -69936,12 +70355,11 @@ var ts; // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file if (!options.lib) { - processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true); + processRootFile(getDefaultLibraryFileName(), /*isDefaultLib*/ true); } else { - var libDirectory_1 = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(host.getDefaultLibFileName(options)); ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(libDirectory_1, libFileName), /*isDefaultLib*/ true); + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true); }); } } @@ -69976,6 +70394,7 @@ var ts; getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, @@ -70267,7 +70686,7 @@ var ts; var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); if (resolveModuleNamesWorker) { - var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, file: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); // ensure that module resolution results are still correct @@ -70344,6 +70763,15 @@ var ts; function isSourceFileFromExternalLibrary(file) { return sourceFilesFoundSearchingNodeModules.get(file.path); } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (defaultLibraryPath && defaultLibraryPath.length !== 0) { + return ts.containsPath(defaultLibraryPath, file.path, currentDirectory, /*ignoreCase*/ !host.useCaseSensitiveFileNames()); + } + return ts.compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } @@ -70485,9 +70913,7 @@ var ts; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - return ts.isSourceFileJavaScript(sourceFile) - ? ts.filter(diagnostics, shouldReportDiagnostic) - : diagnostics; + return ts.filter(diagnostics, shouldReportDiagnostic); }); } /** @@ -70724,16 +71150,15 @@ var ts; return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib); + processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); } function fileReferenceIsEqualTo(a, b) { return a.fileName === b.fileName; } function moduleNameIsEqualTo(a, b) { - return a.text === b.text; - } - function getTextOfLiteral(literal) { - return literal.text; + return a.kind === 9 /* StringLiteral */ + ? b.kind === 9 /* StringLiteral */ && a.text === b.text + : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; } function collectExternalModuleReferences(file) { if (file.imports) { @@ -70789,7 +71214,7 @@ var ts; break; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; // TODO: GH#17347 + var moduleName = node.name; var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: @@ -70869,8 +71294,8 @@ var ts; } } /** This has side effects through `findSourceFile`. */ - function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, /*packageId*/ undefined); }, function (diagnostic) { + function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -70942,7 +71367,7 @@ var ts; } }); if (packageId) { - var packageIdKey = packageId.name + "@" + packageId.version; + var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -70994,7 +71419,7 @@ var ts; function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, file, ref.pos, ref.end); + processSourceFile(referencedFileName, isDefaultLib, /*packageId*/ undefined, file, ref.pos, ref.end); }); } function processTypeReferenceDirectives(file) { @@ -71020,7 +71445,7 @@ var ts; if (resolvedTypeReferenceDirective) { if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } else { // If we already resolved to this file, it must have been a secondary reference. Check file contents @@ -71038,7 +71463,7 @@ var ts; } else { // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, refFile, refPos, refEnd); + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } } @@ -71068,8 +71493,7 @@ var ts; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. - var nonGlobalAugmentation = ts.filter(file.moduleAugmentations, function (moduleAugmentation) { return moduleAugmentation.kind === 9 /* StringLiteral */; }); - var moduleNames = ts.map(ts.concatenate(file.imports, nonGlobalAugmentation), getTextOfLiteral); + var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, file: file, modifiedFilePaths: modifiedFilePaths }; var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); @@ -71080,7 +71504,8 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFileFromNodeModules = isFromNodeModulesSearch && !ts.extensionIsTypeScript(resolution.extension); + var isJsFile = !ts.extensionIsTypeScript(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { currentNodeModulesDepth++; @@ -71093,7 +71518,12 @@ var ts; var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') // This may still end up being an untyped module -- the file won't be included but imports will be allowed. - var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport; + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -71429,7 +71859,7 @@ var ts; return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; } function needAllowJs() { - return options.allowJs ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set; + return options.allowJs || !options.noImplicitAny ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; @@ -71437,6 +71867,18 @@ var ts; ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); return names; } + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } })(ts || (ts = {})); /// /// @@ -72431,7 +72873,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; // Notify key value set, if user asked for it if (jsonConversionNotifier && @@ -72471,7 +72913,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95 /* NullKeyword */: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for return null; // tslint:disable-line:no-null-keyword case 9 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { @@ -72536,6 +72978,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable if (option.type === "list") { return ts.isArray(value); } @@ -72720,6 +73164,15 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } /** * Parse the contents of a config file from json or json source file (tsconfig.json). * @param json The contents of the config file to parse @@ -72752,7 +73205,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -72764,7 +73217,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -72773,7 +73226,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -72790,7 +73243,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -72860,7 +73313,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -72882,7 +73336,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -73038,6 +73493,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -73060,6 +73517,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -73186,7 +73645,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -73871,25 +74330,24 @@ var ts; } ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { - if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { - switch (node.parent.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 264 /* EnumMember */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 233 /* ModuleDeclaration */: - return ts.getNameOfDeclaration(node.parent) === node; - case 180 /* ElementAccessExpression */: - return node.parent.argumentExpression === node; - case 144 /* ComputedPropertyName */: - return true; - } + switch (node.parent.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 261 /* PropertyAssignment */: + case 264 /* EnumMember */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 233 /* ModuleDeclaration */: + return ts.getNameOfDeclaration(node.parent) === node; + case 180 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + case 144 /* ComputedPropertyName */: + return true; + case 173 /* LiteralType */: + return node.parent.parent.kind === 171 /* IndexedAccessType */; } - return false; } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; function isExpressionOfExternalModuleImportEqualsDeclaration(node) { @@ -73969,6 +74427,28 @@ var ts; return "alias" /* alias */; case 283 /* JSDocTypedefTag */: return "type" /* typeElement */; + case 194 /* BinaryExpression */: + var kind = ts.getSpecialPropertyAssignmentKind(node); + var right = node.right; + switch (kind) { + case 0 /* None */: + return "" /* unknown */; + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + var rightKind = getNodeKind(right); + return rightKind === "" /* unknown */ ? "const" /* constElement */ : rightKind; + case 3 /* PrototypeProperty */: + return "method" /* memberFunctionElement */; // instance method + case 4 /* ThisProperty */: + return "property" /* memberVariableElement */; // property + case 5 /* Property */: + // static method / property + return ts.isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; + default: { + ts.assertTypeIsNever(kind); + return "" /* unknown */; + } + } default: return "" /* unknown */; } @@ -74172,7 +74652,7 @@ var ts; return undefined; } var children = list.getChildren(); - var listItemIndex = ts.indexOf(children, node); + var listItemIndex = ts.indexOfNode(children, node); return { listItemIndex: listItemIndex, list: list @@ -74954,7 +75434,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_7 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -74963,8 +75443,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_7, classification: convertClassification(type) }); - lastEnd = start + length_7; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -75517,6 +75997,7 @@ var ts; // specially. var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDoc) { + // TODO: This should be predicated on `token["kind"]` being compatible with `HasJSDoc["kind"]` docCommentAndDiagnostics.jsDoc.parent = token; classifyJSDocComment(docCommentAndDiagnostics.jsDoc); return; @@ -75968,8 +76449,8 @@ var ts; continue; } var start = completePrefix.length; - var length_8 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); + var length_7 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); } return result; } @@ -76263,7 +76744,7 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, @@ -76289,14 +76770,14 @@ var ts; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); + getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -76319,7 +76800,7 @@ var ts; return; } uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true); + var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); if (displayName) { entries.push({ name: displayName, @@ -76330,11 +76811,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { + function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral); if (!displayName) { return undefined; } @@ -76352,13 +76833,13 @@ var ts; sortText: "0", }; } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log) { + function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral) { var start = ts.timestamp(); var uniqueNames = ts.createMap(); if (symbols) { for (var _i = 0, symbols_5 = symbols; _i < symbols_5.length; _i++) { var symbol = symbols_5[_i]; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); + var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral); if (entry) { var id = entry.name; if (!uniqueNames.has(id)) { @@ -76438,7 +76919,7 @@ var ts; var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -76462,7 +76943,7 @@ var ts; var type = typeChecker.getTypeAtLocation(node.expression); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -76493,7 +76974,7 @@ var ts; addStringLiteralCompletionsFromType(t, result, typeChecker, uniques); } } - else if (type.flags & 32 /* StringLiteral */) { + else if (type.flags & 32 /* StringLiteral */ && !(type.flags & 256 /* EnumLiteral */)) { var name = type.value; if (!uniques.has(name)) { uniques.set(name, true); @@ -76510,12 +76991,12 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location = completionData.location; + var symbols = completionData.symbols, location = completionData.location, allowStringLiteral_1 = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral_1) === entryName ? s : undefined; }); if (symbol) { var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { @@ -76546,11 +77027,15 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, allowStringLiteral = completionData.allowStringLiteral; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); + return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { @@ -76618,7 +77103,7 @@ var ts; } } if (request) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, allowStringLiteral: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -76705,6 +77190,7 @@ var ts; var semanticStart = ts.timestamp(); var isGlobalCompletion = false; var isMemberCompletion; + var allowStringLiteral = false; var isNewIdentifierLocation; var keywordFilters = 0 /* None */; var symbols = []; @@ -76740,7 +77226,7 @@ var ts; } } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 277 /* JSDocAugmentsTag */: @@ -77073,6 +77559,7 @@ var ts; function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; + allowStringLiteral = true; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 178 /* ObjectLiteralExpression */) { @@ -77082,7 +77569,7 @@ var ts; var typeForObject = typeChecker.getContextualType(objectLikeContainer); if (!typeForObject) return false; - typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); + typeMembers = getPropertiesForCompletion(typeForObject, typeChecker); existingMembers = objectLikeContainer.properties; } else { @@ -77641,7 +78128,7 @@ var ts; * * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral) { var name = symbol.name; if (!name) return undefined; @@ -77654,19 +78141,20 @@ var ts; return undefined; } } - return getCompletionEntryDisplayName(name, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); } /** * Get a displayName from a given for completion list, performing any necessary quotes stripping * and checking whether the name is valid identifier name. */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return undefined; + // TODO: GH#18169 + return allowStringLiteral ? JSON.stringify(name) : undefined; } return name; } @@ -77773,6 +78261,20 @@ var ts; return node.parent; } } + /** + * Gets all properties on a type, but if that type is a union of several types, + * tries to only include those types which declare properties, not methods. + * This ensures that we don't try providing completions for all the methods on e.g. Array. + */ + function getPropertiesForCompletion(type, checker) { + if (!(type.flags & 65536 /* Union */)) { + return checker.getPropertiesOfType(type); + } + var types = type.types; + var filteredTypes = types.filter(function (memberType) { return !(memberType.flags & 8190 /* Primitive */ || checker.isArrayLikeType(memberType)); }); + // If there are no property-only types, just provide completions for every type as usual. + return checker.getAllPossiblePropertiesOfTypes(filteredTypes); + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -78365,12 +78867,11 @@ var ts; var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); if (!entry) { - ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); entry = { sourceFile: sourceFile, - languageServiceRefCount: 0, + languageServiceRefCount: 1, owners: [] }; bucket.set(path, entry); @@ -78382,14 +78883,14 @@ var ts; if (entry.sourceFile.version !== version) { entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); } - } - // If we're acquiring, then this is the first time this LS is asking for this document. - // Increase our ref count so we know there's another LS using the document. If we're - // not acquiring, then that means the LS is 'updating' the file instead, and that means - // it has already acquired the document previously. As such, we do not need to increase - // the ref count. - if (acquiring) { - entry.languageServiceRefCount++; + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } } return entry.sourceFile; } @@ -78571,7 +79072,6 @@ var ts; * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. */ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { @@ -78603,10 +79103,10 @@ var ts; searchForNamedImport(decl.exportClause); return; } - if (!decl.importClause) { + var importClause = decl.importClause; + if (!importClause) { return; } - var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { handleNamespaceImportLike(namedBindings.name); @@ -78626,7 +79126,6 @@ var ts; } // 'default' might be accessed as a named import `{ default as foo }`. if (!isForRename && exportKind === 1 /* Default */) { - ts.Debug.assert(exportName === "default"); searchForNamedImport(namedBindings); } } @@ -78638,35 +79137,40 @@ var ts; */ function handleNamespaceImportLike(importName) { // Don't rename an import that already has a different name than the export. - if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.escapedText === exportName)) { + if (exportKind === 2 /* ExportEquals */ && (!isForRename || isNameMatch(importName.escapedText))) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) { - for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).escapedText !== exportName) { - continue; - } - if (propertyName) { - // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. - singleReferences.push(propertyName); - if (!isForRename) { - // Search locally for `bar`. - addSearch(name, checker.getSymbolAtLocation(name)); - } - } - else { - var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName - ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. - : checker.getSymbolAtLocation(name); - addSearch(name, localSymbol); + if (!namedBindings) { + return; + } + for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { + var element = _a[_i]; + var name = element.name, propertyName = element.propertyName; + if (!isNameMatch((propertyName || name).escapedText)) { + continue; + } + if (propertyName) { + // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. + singleReferences.push(propertyName); + if (!isForRename) { + // Search locally for `bar`. + addSearch(name, checker.getSymbolAtLocation(name)); } } + else { + var localSymbol = element.kind === 246 /* ExportSpecifier */ && element.propertyName + ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. + : checker.getSymbolAtLocation(name); + addSearch(name, localSymbol); + } } } + function isNameMatch(name) { + // Use name of "default" even in `export =` case because we may have allowSyntheticDefaultImports + return name === exportSymbol.escapedName || exportKind !== 0 /* Named */ && name === "default"; + } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { @@ -78842,7 +79346,8 @@ var ts; // Get the symbol for the `export =` node; its parent is the module it's the export of. var exportingModuleSymbol = ex.symbol.parent; ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; @@ -78874,7 +79379,11 @@ var ts; if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } - if (symbolName(importedSymbol) === symbol.escapedName) { + // If the import has a different name than the export, do not continue searching. + // If `importedName` is undefined, do continue searching as the export is anonymous. + // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) + var importedName = symbolName(importedSymbol); + if (importedName === undefined || importedName === "default" || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } @@ -79066,8 +79575,8 @@ var ts; case "symbol": { var symbol = def.symbol, node_2 = def.node; var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: node_2, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -79075,8 +79584,8 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; @@ -79117,8 +79626,10 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), - isWriteAccess: isWriteAccess(node), - isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isWriteAccess: isWriteAccessForReference(node), + isDefinition: node.kind === 79 /* DefaultKeyword */ + || ts.isAnyDeclarationName(node) + || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -79160,7 +79671,7 @@ var ts; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; - var writeAccess = isWriteAccess(node); + var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, @@ -79179,20 +79690,8 @@ var ts; return ts.createTextSpanFromBounds(start, end); } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ - function isWriteAccess(node) { - if (ts.isAnyDeclarationName(node)) { - return true; - } - var parent = node.parent; - switch (parent && parent.kind) { - case 193 /* PostfixUnaryExpression */: - case 192 /* PrefixUnaryExpression */: - return true; - case 194 /* BinaryExpression */: - return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); - default: - return false; - } + function isWriteAccessForReference(node) { + return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -79617,7 +80116,7 @@ var ts; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for - switch (node && node.kind) { + switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; case 9 /* StringLiteral */: @@ -79625,6 +80124,8 @@ var ts; node.text.length === searchSymbolName.length; case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; + case 79 /* DefaultKeyword */: + return "default".length === searchSymbolName.length; default: return false; } @@ -80237,20 +80738,24 @@ var ts; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); if (bindingElementPropertySymbol) { result.push(bindingElementPropertySymbol); + addRootSymbols(bindingElementPropertySymbol); } - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - for (var _i = 0, _a = checker.getRootSymbols(symbol); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - if (rootSymbol !== symbol) { - result.push(rootSymbol); - } - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); + addRootSymbols(symbol); + return result; + function addRootSymbols(sym) { + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list + for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { + var rootSymbol = _a[_i]; + if (rootSymbol !== sym) { + result.push(rootSymbol); + } + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); + } } } - return result; } /** * Find symbol of the given property-name and add the symbol to the given result array @@ -80333,30 +80838,35 @@ var ts; // then include the binding element in the related symbols // let { a } : { a }; var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker); - if (bindingElementPropertySymbol && search.includes(bindingElementPropertySymbol)) { - return bindingElementPropertySymbol; - } - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.forEach(state.checker.getRootSymbols(referenceSymbol), function (rootSymbol) { - // if it is in the list, then we are done - if (search.includes(rootSymbol)) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the - // parent symbol - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { - return undefined; + if (bindingElementPropertySymbol) { + var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); + if (fromBindingElement) + return fromBindingElement; + } + return findRootSymbol(referenceSymbol); + function findRootSymbol(sym) { + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols + return ts.forEach(state.checker.getRootSymbols(sym), function (rootSymbol) { + // if it is in the list, then we are done + if (search.includes(rootSymbol)) { + return rootSymbol; + } + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the + // parent symbol + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + // Parents will only be defined if implementations is true + if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) { + return undefined; + } + var result = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); + return ts.find(result, search.includes); } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); - return ts.find(result, search.includes); - } - return undefined; - }); + return undefined; + }); + } } function getNameFromObjectLiteralElement(node) { if (node.name.kind === 144 /* ComputedPropertyName */) { @@ -80979,52 +81489,32 @@ var ts; if (!tokenAtPos || tokenStart < position) { return undefined; } - // TODO: add support for: - // - enums/enum members - // - interfaces - // - property declarations - // - potentially property assignments - var commentOwner; - findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { - switch (commentOwner.kind) { - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 152 /* Constructor */: - case 229 /* ClassDeclaration */: - case 208 /* VariableStatement */: - break findOwner; - case 265 /* SourceFile */: - return undefined; - case 233 /* ModuleDeclaration */: - // If in walking up the tree, we hit a a nested namespace declaration, - // then we must be somewhere within a dotted namespace name; however we don't - // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - if (commentOwner.parent.kind === 233 /* ModuleDeclaration */) { - return undefined; - } - break findOwner; - } + var commentOwnerInfo = getCommentOwnerInfo(tokenAtPos); + if (!commentOwnerInfo) { + return undefined; } - if (!commentOwner || commentOwner.getStart() < position) { + var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; + if (commentOwner.getStart() < position) { return undefined; } - var parameters = getParametersForJsDocOwningNode(commentOwner); var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; // replace non-whitespace characters in prefix with spaces. var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.escapedText : - "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; + if (parameters) { + for (var i = 0; i < parameters.length; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 71 /* Identifier */ ? + currentName.escapedText : + "param" + i; + if (isJavaScriptFile) { + docParams += indentationStr + " * @param {any} " + paramName + newLine; + } + else { + docParams += indentationStr + " * @param " + paramName + newLine; + } } } // A doc comment consists of the following @@ -81043,18 +81533,46 @@ var ts; return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; - function getParametersForJsDocOwningNode(commentOwner) { - if (ts.isFunctionLike(commentOwner)) { - return commentOwner.parameters; - } - if (commentOwner.kind === 208 /* VariableStatement */) { - var varStatement = commentOwner; - var varDeclarations = varStatement.declarationList.declarations; - if (varDeclarations.length === 1 && varDeclarations[0].initializer) { - return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + function getCommentOwnerInfo(tokenAtPos) { + // TODO: add support for: + // - enums/enum members + // - interfaces + // - property declarations + // - potentially property assignments + for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 152 /* Constructor */: + var parameters = commentOwner.parameters; + return { commentOwner: commentOwner, parameters: parameters }; + case 229 /* ClassDeclaration */: + return { commentOwner: commentOwner }; + case 208 /* VariableStatement */: { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + ? getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer) + : undefined; + return { commentOwner: commentOwner, parameters: parameters_1 }; + } + case 265 /* SourceFile */: + return undefined; + case 233 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + return commentOwner.parent.kind === 233 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 194 /* BinaryExpression */: { + var be = commentOwner; + if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + return undefined; + } + var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; + return { commentOwner: commentOwner, parameters: parameters_2 }; + } } } - return ts.emptyArray; } /** * Digs into an an initializer or RHS operand of an assignment operation @@ -81303,32 +81821,7 @@ var ts; return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { - if (declarations) { - // First do a quick check to see if the name of the declaration matches the - // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { - return; // continue to next named declarations - } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - // It was a match! If the pattern has dots in it, then also see if the - // declaration container matches as well. - if (patternMatcher.patternContainsDots) { - var containers = getContainers(declaration); - if (!containers) { - return true; // Break out of named declarations and go to the next source file. - } - matches = patternMatcher.getMatches(containers, name); - if (!matches) { - return; // continue to next named declarations - } - } - var fileName = sourceFile.fileName; - var matchKind = bestMatchKind(matches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); - } - } + getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] @@ -81336,134 +81829,159 @@ var ts; var sourceFile = sourceFiles_8[_i]; _loop_6(sourceFile); } - // Remove imports when the imported declaration is already in the list and has the same name. - rawItems = ts.filter(rawItems, function (item) { - var decl = item.declaration; - if (decl.kind === 239 /* ImportClause */ || decl.kind === 242 /* ImportSpecifier */ || decl.kind === 237 /* ImportEqualsDeclaration */) { - var importer = checker.getSymbolAtLocation(decl.name); - var imported = checker.getAliasedSymbol(importer); - return importer.escapedName !== imported.escapedName; - } - else { - return true; - } - }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); } - var items = ts.map(rawItems, createNavigateToItem); - return items; - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - if (!match.isCaseSensitive) { - return false; - } + return rawItems.map(createNavigateToItem); + } + NavigateTo.getNavigateToItems = getNavigateToItems; + function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); + if (!matches) { + return; // continue to next named declarations + } + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; + if (!shouldKeepItem(declaration, checker)) { + continue; } - return true; - } - function tryAddSingleDeclarationName(declaration, containers) { - if (declaration) { - var name = ts.getNameOfDeclaration(declaration); - if (name) { - var text = ts.getTextOfIdentifierOrLiteral(name); - if (text !== undefined) { - containers.unshift(text); - } - else if (name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; - } + // It was a match! If the pattern has dots in it, then also see if the + // declaration container matches as well. + var containerMatches = matches; + if (patternMatcher.patternContainsDots) { + containerMatches = patternMatcher.getMatches(getContainers(declaration), name); + if (!containerMatches) { + continue; } } - return true; + var matchKind = bestMatchKind(containerMatches); + var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); + rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); } - // Only added the names of computed properties if they're simple dotted expressions, like: - // - // [X.Y.Z]() { } - function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = ts.getTextOfIdentifierOrLiteral(expression); - if (text !== undefined) { - if (includeLastPortion) { - containers.unshift(text); - } + } + function shouldKeepItem(declaration, checker) { + switch (declaration.kind) { + case 239 /* ImportClause */: + case 242 /* ImportSpecifier */: + case 237 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); + var imported = checker.getAliasedSymbol(importer); + return importer.escapedName !== imported.escapedName; + default: return true; + } + } + function allMatchesAreCaseSensitive(matches) { + ts.Debug.assert(matches.length > 0); + // This is a case sensitive match, only if all the submatches were case sensitive. + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; + if (!match.isCaseSensitive) { + return false; } - if (expression.kind === 179 /* PropertyAccessExpression */) { - var propertyAccess = expression; - if (includeLastPortion) { - containers.unshift(propertyAccess.name.text); - } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); - } - return false; } - function getContainers(declaration) { - var containers = []; - // First, if we started with a computed property name, then add all but the last - // portion into the container array. + return true; + } + function tryAddSingleDeclarationName(declaration, containers) { + if (declaration) { var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { - return undefined; + if (name) { + var text = ts.getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); } - } - // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; } - declaration = ts.getContainerNode(declaration); } - return containers; } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } + return true; + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers, includeLastPortion) { + var text = ts.getTextOfIdentifierOrLiteral(expression); + if (text !== undefined) { + if (includeLastPortion) { + containers.unshift(text); + } + return true; + } + if (expression.kind === 179 /* PropertyAccessExpression */) { + var propertyAccess = expression; + if (includeLastPortion) { + containers.unshift(propertyAccess.name.text); } - return bestMatchKind; + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } - function compareNavigateToItems(i1, i2) { - // TODO(cyrusn): get the gamut of comparisons that VS already uses here. - // Right now we just sort by kind first, and then by name of the item. - // We first sort case insensitively. So "Aaa" will come before "bar". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - return i1.matchKind - i2.matchKind || - ts.compareStringsCaseInsensitive(i1.name, i2.name) || - ts.compareStrings(i1.name, i2.name); + return false; + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + return undefined; + } } - function createNavigateToItem(rawItem) { - var declaration = rawItem.declaration; - var container = ts.getContainerNode(declaration); - var containerName = container && ts.getNameOfDeclaration(container); - return { - name: rawItem.name, - kind: ts.getNodeKind(declaration), - kindModifiers: ts.getNodeModifiers(declaration), - matchKind: ts.PatternMatchKind[rawItem.matchKind], - isCaseSensitive: rawItem.isCaseSensitive, - fileName: rawItem.fileName, - textSpan: ts.createTextSpanFromNode(declaration), - // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ - }; + // Now, walk up our containers, adding all their names to the container array. + declaration = ts.getContainerNode(declaration); + while (declaration) { + if (!tryAddSingleDeclarationName(declaration, containers)) { + return undefined; + } + declaration = ts.getContainerNode(declaration); } + return containers; + } + function bestMatchKind(matches) { + ts.Debug.assert(matches.length > 0); + var bestMatchKind = ts.PatternMatchKind.camelCase; + for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { + var match = matches_3[_i]; + var kind = match.kind; + if (kind < bestMatchKind) { + bestMatchKind = kind; + } + } + return bestMatchKind; + } + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + // Right now we just sort by kind first, and then by name of the item. + // We first sort case insensitively. So "Aaa" will come before "bar". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + return i1.matchKind - i2.matchKind || + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromNode(declaration), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + }; } - NavigateTo.getNavigateToItems = getNavigateToItems; })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); /// @@ -81647,17 +82165,24 @@ var ts; break; case 176 /* BindingElement */: case 226 /* VariableDeclaration */: - var decl = node; - var name = decl.name; + var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); } - else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { - // For `const x = function() {}`, just use the function node, not the const. - addChildrenRecursively(decl.initializer); + else if (initializer && isFunctionOrClassExpression(initializer)) { + if (initializer.name) { + // Don't add a node for the VariableDeclaration, just for the initializer. + addChildrenRecursively(initializer); + } + else { + // Add a node for the VariableDeclaration, but not for the initializer. + startNode(node); + ts.forEachChild(initializer, addChildrenRecursively); + endNode(); + } } else { - addNodeWithRecursiveChild(decl, decl.initializer); + addNodeWithRecursiveChild(node, initializer); } break; case 187 /* ArrowFunction */: @@ -81667,8 +82192,8 @@ var ts; break; case 232 /* EnumDeclaration */: startNode(node); - for (var _d = 0, _e = node.members; _d < _e.length; _d++) { - var member = _e[_d]; + for (var _e = 0, _f = node.members; _e < _f.length; _e++) { + var member = _f[_e]; if (!isComputedProperty(member)) { addLeafNode(member); } @@ -81679,8 +82204,8 @@ var ts; case 199 /* ClassExpression */: case 230 /* InterfaceDeclaration */: startNode(node); - for (var _f = 0, _g = node.members; _f < _g.length; _f++) { - var member = _g[_f]; + for (var _g = 0, _h = node.members; _g < _h.length; _g++) { + var member = _h[_g]; addChildrenRecursively(member); } endNode(); @@ -81697,13 +82222,15 @@ var ts; addLeafNode(node); break; default: - ts.forEach(node.jsDoc, function (jsDoc) { - ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 283 /* JSDocTypedefTag */) { - addLeafNode(tag); - } + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, function (jsDoc) { + ts.forEach(jsDoc.tags, function (tag) { + if (tag.kind === 283 /* JSDocTypedefTag */) { + addLeafNode(tag); + } + }); }); - }); + } ts.forEachChild(node, addChildrenRecursively); } } @@ -82038,7 +82565,14 @@ var ts; } } function isFunctionOrClassExpression(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */ || node.kind === 199 /* ClassExpression */; + switch (node.kind) { + case 187 /* ArrowFunction */: + case 186 /* FunctionExpression */: + case 199 /* ClassExpression */: + return true; + default: + return false; + } } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); @@ -82049,11 +82583,15 @@ var ts; (function (OutliningElementsCollector) { var collapseText = "..."; var maxDepth = 20; + var defaultLabel = "#region"; + var regionMatch = new RegExp("^\\s*//\\s*#(end)?region(?:\\s+(.*))?$"); function collectElements(sourceFile, cancellationToken) { var elements = []; var depth = 0; + var regions = []; walk(sourceFile); - return elements; + gatherRegions(); + return elements.sort(function (span1, span2) { return span1.textSpan.start - span2.textSpan.start; }); /** If useFullStart is true, then the collapsing span includes leading whitespace, including linebreaks. */ function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse, useFullStart) { if (hintSpanNode && startElement && endElement) { @@ -82122,6 +82660,36 @@ var ts; function autoCollapse(node) { return ts.isFunctionBlock(node) && node.parent.kind !== 187 /* ArrowFunction */; } + function gatherRegions() { + var lineStarts = sourceFile.getLineStarts(); + for (var i = 0; i < lineStarts.length; i++) { + var currentLineStart = lineStarts[i]; + var lineEnd = lineStarts[i + 1] - 1 || sourceFile.getEnd(); + var comment = sourceFile.text.substring(currentLineStart, lineEnd); + var result = comment.match(regionMatch); + if (result && !ts.isInComment(sourceFile, currentLineStart)) { + if (!result[1]) { + var start = sourceFile.getFullText().indexOf("//", currentLineStart); + var textSpan = ts.createTextSpanFromBounds(start, lineEnd); + var region = { + textSpan: textSpan, + hintSpan: textSpan, + bannerText: result[2] || defaultLabel, + autoCollapse: false + }; + regions.push(region); + } + else { + var region = regions.pop(); + if (region) { + region.textSpan.length = lineEnd - region.textSpan.start; + region.hintSpan.length = lineEnd - region.textSpan.start; + elements.push(region); + } + } + } + } + } function walk(n) { cancellationToken.throwIfCancellationRequested(); if (depth > maxDepth) { @@ -83030,13 +83598,11 @@ var ts; } // skip open bracket token = nextToken(); - var i = 0; // scan until ']' or EOF while (token !== 22 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names if (token === 9 /* StringLiteral */) { recordModuleName(); - i++; } token = nextToken(); } @@ -83197,10 +83763,16 @@ var ts; return ts.createTextSpan(start, width); } function nodeIsEligibleForRename(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || - ts.isThis(node); + switch (node.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 99 /* ThisKeyword */: + return true; + case 8 /* NumericLiteral */: + return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node); + default: + return false; + } } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); @@ -83537,8 +84109,7 @@ var ts; if (isTypeParameterList) { isVariadic = false; // type parameter lists are not variadic prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - // Use `.mapper` to ensure we get the generic type arguments even if this is an instantiated version of the signature. - var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + var typeParameters = (candidateSignature.target || candidateSignature).typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { @@ -83676,7 +84247,8 @@ var ts; if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { return "property" /* memberVariableElement */; } - ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); + // May be a Function if this was from `typeof N` with `namespace N { function f();. }`. + ts.Debug.assert(!!(rootSymbolFlags & (8192 /* Method */ | 16 /* Function */))); }); if (!unionPropertyKind) { // If this was union of all methods, @@ -84270,10 +84842,6 @@ var ts; (function (formatting) { var standardScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); var jsxScanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); - /** - * Scanner that is currently used for formatting - */ - var scanner; var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -84283,9 +84851,8 @@ var ts; ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText"; })(ScanAction || (ScanAction = {})); - function getFormattingScanner(text, languageVariant, startPos, endPos) { - ts.Debug.assert(scanner === undefined, "Scanner should be undefined"); - scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + function getFormattingScanner(text, languageVariant, startPos, endPos, cb) { + var scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; scanner.setText(text); scanner.setTextPos(startPos); var wasNewLine = true; @@ -84294,38 +84861,28 @@ var ts; var savedPos; var lastScanAction; var lastTokenInfo; - return { + var res = cb({ advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, - close: function () { - ts.Debug.assert(scanner !== undefined); - lastTokenInfo = undefined; - scanner.setText(undefined); - scanner = undefined; - } - }; + }); + lastTokenInfo = undefined; + scanner.setText(undefined); + return res; function advance() { - ts.Debug.assert(scanner !== undefined, "Scanner should be present"); lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - if (trailingTrivia) { - ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; - } - else { - wasNewLine = false; - } + wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; } - leadingTrivia = undefined; - trailingTrivia = undefined; - if (!isStarted) { + else { scanner.scan(); } + leadingTrivia = undefined; + trailingTrivia = undefined; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { @@ -84341,23 +84898,18 @@ var ts; kind: t }; pos = scanner.getStartPos(); - if (!leadingTrivia) { - leadingTrivia = []; - } - leadingTrivia.push(item); + leadingTrivia = ts.append(leadingTrivia, item); } savedPos = scanner.getStartPos(); } function shouldRescanGreaterThanToken(node) { - if (node) { - switch (node.kind) { - case 31 /* GreaterThanEqualsToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - return true; - } + switch (node.kind) { + case 31 /* GreaterThanEqualsToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + return true; } return false; } @@ -84368,13 +84920,14 @@ var ts; case 251 /* JsxOpeningElement */: case 252 /* JsxClosingElement */: case 250 /* JsxSelfClosingElement */: - return node.kind === 71 /* Identifier */; + // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. + return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } } return false; } function shouldRescanJsxText(node) { - return node && node.kind === 10 /* JsxText */; + return node.kind === 10 /* JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 12 /* RegularExpressionLiteral */; @@ -84387,15 +84940,7 @@ var ts; return t === 41 /* SlashToken */ || t === 63 /* SlashEqualsToken */; } function readTokenInfo(n) { - ts.Debug.assert(scanner !== undefined); - if (!isOnToken()) { - // scanner is not on the token (either advance was not called yet or scanner is already past the end position) - return { - leadingTrivia: leadingTrivia, - trailingTrivia: undefined, - token: undefined - }; - } + ts.Debug.assert(isOnToken()); // normally scanner returns the smallest available token // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. var expectedScanAction = shouldRescanGreaterThanToken(n) @@ -84424,32 +84969,7 @@ var ts; scanner.setTextPos(savedPos); scanner.scan(); } - var currentToken = scanner.getToken(); - if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 29 /* GreaterThanToken */) { - currentToken = scanner.reScanGreaterToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 1 /* RescanGreaterThanToken */; - } - else if (expectedScanAction === 2 /* RescanSlashToken */ && startsWithSlashToken(currentToken)) { - currentToken = scanner.reScanSlashToken(); - ts.Debug.assert(n.kind === currentToken); - lastScanAction = 2 /* RescanSlashToken */; - } - else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 18 /* CloseBraceToken */) { - currentToken = scanner.reScanTemplateToken(); - lastScanAction = 3 /* RescanTemplateToken */; - } - else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 71 /* Identifier */) { - currentToken = scanner.scanJsxIdentifier(); - lastScanAction = 4 /* RescanJsxIdentifier */; - } - else if (expectedScanAction === 5 /* RescanJsxText */) { - currentToken = scanner.reScanJsxToken(); - lastScanAction = 5 /* RescanJsxText */; - } - else { - lastScanAction = 0 /* Scan */; - } + var currentToken = getNextToken(n, expectedScanAction); var token = { pos: scanner.getStartPos(), end: scanner.getTextPos(), @@ -84482,8 +85002,46 @@ var ts; lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } + function getNextToken(n, expectedScanAction) { + var token = scanner.getToken(); + lastScanAction = 0 /* Scan */; + switch (expectedScanAction) { + case 1 /* RescanGreaterThanToken */: + if (token === 29 /* GreaterThanToken */) { + lastScanAction = 1 /* RescanGreaterThanToken */; + var newToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 2 /* RescanSlashToken */: + if (startsWithSlashToken(token)) { + lastScanAction = 2 /* RescanSlashToken */; + var newToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === newToken); + return newToken; + } + break; + case 3 /* RescanTemplateToken */: + if (token === 18 /* CloseBraceToken */) { + lastScanAction = 3 /* RescanTemplateToken */; + return scanner.reScanTemplateToken(); + } + break; + case 4 /* RescanJsxIdentifier */: + lastScanAction = 4 /* RescanJsxIdentifier */; + return scanner.scanJsxIdentifier(); + case 5 /* RescanJsxText */: + lastScanAction = 5 /* RescanJsxText */; + return scanner.reScanJsxToken(); + case 0 /* Scan */: + break; + default: + ts.Debug.assertNever(expectedScanAction); + } + return token; + } function isOnToken() { - ts.Debug.assert(scanner !== undefined); var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); @@ -84623,11 +85181,6 @@ var ts; this.Operation = Operation; this.Flag = Flag; } - Rule.prototype.toString = function () { - return "[desc=" + this.Descriptor + "," + - "operation=" + this.Operation + "," + - "flag=" + this.Flag + "]"; - }; return Rule; }()); formatting.Rule = Rule; @@ -85021,16 +85574,16 @@ var ts; this.SpaceAfterSemicolon, this.SpaceBetweenStatements, this.SpaceAfterTryFinally ]; - } - Rules.prototype.getRuleName = function (rule) { - var o = this; - for (var name in o) { - if (o[name] === rule) { - return name; + if (ts.Debug.isDebugging) { + var o = this; + for (var name in o) { + var rule = o[name]; + if (rule instanceof formatting.Rule) { + rule.debugName = name; + } } } - throw new Error("Unknown rule"); - }; + } /// /// Contexts /// @@ -85188,8 +85741,8 @@ var ts; return true; case 207 /* Block */: { var blockParent = context.currentTokenParent.parent; - if (blockParent.kind !== 187 /* ArrowFunction */ && - blockParent.kind !== 186 /* FunctionExpression */) { + // In a codefix scenario, we can't rely on parents being set. So just always return true. + if (!blockParent || blockParent.kind !== 187 /* ArrowFunction */ && blockParent.kind !== 186 /* FunctionExpression */) { return true; } } @@ -85635,15 +86188,9 @@ var ts; var RulesProvider = /** @class */ (function () { function RulesProvider() { this.globalRules = new formatting.Rules(); - var activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); + var activeRules = this.globalRules.HighPriorityCommonRules.concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); this.rulesMap = formatting.RulesMap.create(activeRules); } - RulesProvider.prototype.getRuleName = function (rule) { - return this.globalRules.getRuleName(rule); - }; - RulesProvider.prototype.getRuleByName = function (name) { - return this.globalRules[name]; - }; RulesProvider.prototype.getRulesMap = function () { return this.rulesMap; }; @@ -85918,8 +86465,8 @@ var ts; /* @internal */ function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; - return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors - sourceFileLike); + return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors + sourceFileLike); }); } formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { @@ -85935,7 +86482,7 @@ var ts; function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); - return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); + return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), scanner, options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) { // formatting context is used by rules provider @@ -85962,7 +86509,6 @@ var ts; trimTrailingWhitespacesForRemainingRange(); } } - formattingScanner.close(); return edits; // local functions /** Tries to compute the indentation for a list element. @@ -86201,6 +86747,7 @@ var ts; return inheritedIndentation; } function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; @@ -87120,6 +87667,8 @@ var ts; case 241 /* NamedImports */: case 246 /* ExportSpecifier */: case 242 /* ImportSpecifier */: + case 261 /* PropertyAssignment */: + case 149 /* PropertyDeclaration */: return true; } return false; @@ -87174,15 +87723,21 @@ var ts; * It can be changed to side-table later if we decide that current design is too invasive. */ function getPos(n) { - return n["__pos"]; + var result = n["__pos"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setPos(n, pos) { + ts.Debug.assert(typeof pos === "number"); n["__pos"] = pos; } function getEnd(n) { - return n["__end"]; + var result = n["__end"]; + ts.Debug.assert(typeof result === "number"); + return result; } function setEnd(n, end) { + ts.Debug.assert(typeof end === "number"); n["__end"] = end; } var Position; @@ -87237,7 +87792,9 @@ var ts; return position === Position.Start ? start : fullStart; } // get start position of the line following the line that contains fullstart position - var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + 1, sourceFile); + // (but only if the fullstart isn't the very beginning of the file) + var nextLineStart = fullStart > 0 ? 1 : 0; + var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile); // skip whitespaces/newlines adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); @@ -87267,9 +87824,6 @@ var ts; } return s; } - function getNewlineKind(context) { - return context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - } var ChangeTracker = /** @class */ (function () { function ChangeTracker(newLine, rulesProvider, validator) { this.newLine = newLine; @@ -87278,8 +87832,8 @@ var ts; this.changes = []; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } - ChangeTracker.fromCodeFixContext = function (context) { - return new ChangeTracker(getNewlineKind(context), context.rulesProvider); + ChangeTracker.fromContext = function (context) { + return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider); }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); @@ -87305,7 +87859,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(node); + var index = ts.indexOfNode(containingList, node); if (index < 0) { return this; } @@ -87430,7 +87984,7 @@ var ts; ts.Debug.fail("node is not a list element"); return this; } - var index = containingList.indexOf(after); + var index = ts.indexOfNode(containingList, after); if (index < 0) { return this; } @@ -87646,10 +88200,9 @@ var ts; var options = { newLine: newLine, target: sourceFile && sourceFile.languageVersion }; var writer = new Writer(ts.getNewLineCharacter(options)); var printer = ts.createPrinter(options, writer); - printer.writeNode(3 /* Unspecified */, node, sourceFile, writer); + printer.writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } - textChanges.getNonformattedText = getNonformattedText; function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) { var lineMap = ts.computeLineStarts(nonFormattedText.text); var file = { @@ -87660,7 +88213,6 @@ var ts; var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } - textChanges.applyFormatting = applyFormatting; function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var change = changes[i]; @@ -87675,13 +88227,10 @@ var ts; function assignPositionsToNode(node) { var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes - var newNode = ts.nodeIsSynthesized(visited) - ? visited - : (Proxy.prototype = visited, new Proxy()); + var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); newNode.end = getEnd(node); return newNode; - function Proxy() { } } function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); @@ -87817,7 +88366,15 @@ var ts; ts.forEach(fixes, function (f) { var actions = f.getCodeActions(context); if (actions && actions.length > 0) { - allActions = allActions.concat(actions); + for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { + var action = actions_1[_i]; + if (action === undefined) { + context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); + } + else { + allActions.push(action); + } + } } }); return allActions; @@ -87849,6 +88406,10 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); + function getRefactorContextLength(context) { + return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + } + ts.getRefactorContextLength = getRefactorContextLength; })(ts || (ts = {})); /* @internal */ var ts; @@ -87868,7 +88429,7 @@ var ts; var leftText = qualifiedName.left.getText(sourceFile); var rightText = qualifiedName.right.getText(sourceFile); var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); return [{ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), @@ -88006,7 +88567,7 @@ var ts; } var className = classDeclaration.name.getText(); var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); - var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); var initializeStaticAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), @@ -88021,7 +88582,7 @@ var ts; return actions; } var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); - var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var initializeAction = { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), @@ -88051,7 +88612,7 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var propertyChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); (actions || (actions = [])).push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), @@ -88069,7 +88630,7 @@ var ts; var indexSignature = ts.createIndexSignature( /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); - var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), @@ -88082,7 +88643,7 @@ var ts; if (token.parent.parent.kind === 181 /* CallExpression */) { var callExpression = token.parent.parent; var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); - var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromContext(context); methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? @@ -88225,7 +88786,7 @@ var ts; } } } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); changeTracker.deleteNode(sourceFile, superCall); return [{ @@ -88258,7 +88819,7 @@ var ts; if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); return [{ @@ -88292,7 +88853,7 @@ var ts; if (!(extendsToken && extendsToken.kind === 85 /* ExtendsKeyword */)) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // We replace existing keywords with commas. for (var i = 1; i < heritageClauses.length; i++) { @@ -88323,7 +88884,7 @@ var ts; if (token.kind !== 71 /* Identifier */) { return undefined; } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token)); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), @@ -88340,8 +88901,8 @@ var ts; (function (codefix) { codefix.registerCodeFix({ errorCodes: [ - ts.Diagnostics._0_is_declared_but_never_used.code, - ts.Diagnostics.Property_0_is_declared_but_never_used.code + ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code ], getCodeActions: function (context) { var sourceFile = context.sourceFile; @@ -88491,19 +89052,19 @@ var ts; } } function deleteNode(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNode(sourceFile, n)); } function deleteRange(range) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteRange(sourceFile, range)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteRange(sourceFile, range)); } function deleteNodeInList(n) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeInList(sourceFile, n)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeInList(sourceFile, n)); } function deleteNodeRange(start, end) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeRange(sourceFile, start, end)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).deleteNodeRange(sourceFile, start, end)); } function replaceNode(n, newNode) { - return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); + return makeChange(ts.textChanges.ChangeTracker.fromContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { return { @@ -88527,11 +89088,32 @@ var ts; function getActionsForJSDocTypes(context) { var sourceFile = context.sourceFile; var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); - var decl = ts.findAncestor(node, function (n) { return n.kind === 226 /* VariableDeclaration */; }); + // NOTE: Some locations are not handled yet: + // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments + var decl = ts.findAncestor(node, function (n) { + return n.kind === 202 /* AsExpression */ || + n.kind === 155 /* CallSignature */ || + n.kind === 156 /* ConstructSignature */ || + n.kind === 228 /* FunctionDeclaration */ || + n.kind === 153 /* GetAccessor */ || + n.kind === 157 /* IndexSignature */ || + n.kind === 172 /* MappedType */ || + n.kind === 151 /* MethodDeclaration */ || + n.kind === 150 /* MethodSignature */ || + n.kind === 146 /* Parameter */ || + n.kind === 149 /* PropertyDeclaration */ || + n.kind === 148 /* PropertySignature */ || + n.kind === 154 /* SetAccessor */ || + n.kind === 231 /* TypeAliasDeclaration */ || + n.kind === 184 /* TypeAssertionExpression */ || + n.kind === 226 /* VariableDeclaration */; + }); if (!decl) return; var checker = context.program.getTypeChecker(); var jsdocType = decl.type; + if (!jsdocType) + return; var original = ts.getTextOfNode(jsdocType); var type = checker.getTypeFromTypeNode(jsdocType); var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; @@ -88734,28 +89316,21 @@ var ts; if (cached) { return cached; } - var existingDeclarations = []; - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importModuleSpecifier = _a[_i]; - var importSymbol = checker.getSymbolAtLocation(importModuleSpecifier); - if (importSymbol === moduleSymbol) { - existingDeclarations.push(getImportDeclaration(importModuleSpecifier)); - } - } + var existingDeclarations = ts.mapDefined(sourceFile.imports, function (importModuleSpecifier) { + return checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; + }); cachedImportDeclarations[moduleSymbolId] = existingDeclarations; return existingDeclarations; - function getImportDeclaration(moduleSpecifier) { - var node = moduleSpecifier; - while (node) { - if (node.kind === 238 /* ImportDeclaration */) { - return node; - } - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - node = node.parent; + function getImportDeclaration(_a) { + var parent = _a.parent; + switch (parent.kind) { + case 238 /* ImportDeclaration */: + return parent; + case 248 /* ExternalModuleReference */: + return parent.parent; + default: + return undefined; } - return undefined; } } function getUniqueSymbolId(symbol) { @@ -89164,7 +89739,7 @@ var ts; } } function createChangeTracker() { - return ts.textChanges.ChangeTracker.fromCodeFixContext(context); + return ts.textChanges.ChangeTracker.fromContext(context); } function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) { return { @@ -89251,7 +89826,7 @@ var ts; (function (codefix) { function newNodesToChanges(newNodes, insertAfter, context) { var sourceFile = context.sourceFile; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) { var newNode = newNodes_1[_i]; changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter }); @@ -89538,7 +90113,7 @@ var ts; return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { @@ -89568,7 +90143,9 @@ var ts; deleteCallback(); } return { - edits: changeTracker.getChanges() + edits: changeTracker.getChanges(), + renameFilename: undefined, + renameLocation: undefined, }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } @@ -89730,7 +90307,7 @@ var ts; refactor.registerRefactor(extractMethod); /** Compute the associated code actions */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: context.endPosition - context.startPosition }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -89744,15 +90321,15 @@ var ts; var usedNames = ts.createMap(); var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { - var extr = extractions_1[_i]; + var _a = extractions_1[_i], scopeDescription = _a.scopeDescription, errors = _a.errors; // Skip these since we don't have a way to report errors yet - if (extr.errors && extr.errors.length) { + if (errors.length) { continue; } // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_function_into_0.message, [extr.scopeDescription]); + var description = ts.formatStringFromArgs(ts.Diagnostics.Extract_to_0.message, [scopeDescription]); if (!usedNames.has(description)) { usedNames.set(description, true); actions.push({ @@ -89775,17 +90352,13 @@ var ts; }]; } function getEditsForAction(context, actionName) { - var length = context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: length }); + var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; var parsedIndexMatch = /^scope_(\d+)$/.exec(actionName); ts.Debug.assert(!!parsedIndexMatch, "Scope name should have matched the regexp"); var index = +parsedIndexMatch[1]; ts.Debug.assert(isFinite(index), "Expected to parse a finite number from the scope index"); - var extractions = getPossibleExtractions(targetRange, context, index); - // Scope is no longer valid from when the user issued the refactor (??) - ts.Debug.assert(extractions !== undefined, "The extraction went missing? How?"); - return ({ edits: extractions[0].changes }); + return getExtractionAtIndex(targetRange, context, index); } // Move these into diagnostic messages if they become user-facing var Messages; @@ -89818,15 +90391,19 @@ var ts; * The range is in a function which needs the 'static' modifier in a class */ RangeFacts[RangeFacts["InStaticRegion"] = 16] = "InStaticRegion"; - })(RangeFacts = extractMethod_1.RangeFacts || (extractMethod_1.RangeFacts = {})); + })(RangeFacts || (RangeFacts = {})); /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This * process may fail, in which case a set of errors is returned instead (these are currently * not shown to the user, but can be used by us diagnostically) */ + // exported only for tests function getRangeToExtract(sourceFile, span) { - var length = span.length || 0; + var length = span.length; + if (length === 0) { + return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.StatementOrExpressionExpected)] }; + } // Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span. // This may fail (e.g. you select two statements in the root of a source file) var start = getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false), sourceFile, span); @@ -89893,22 +90470,13 @@ var ts; if (errors) { return { errors: errors }; } - // If our selection is the expression in an ExpressionStatement, expand - // the selection to include the enclosing Statement (this stops us - // from trying to care about the return value of the extracted function - // and eliminates double semicolon insertion in certain scenarios) - var range = ts.isStatement(start) - ? [start] - : start.parent && start.parent.kind === 210 /* ExpressionStatement */ - ? [start.parent] - : start; - return { targetRange: { range: range, facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(start), facts: rangeFacts, declarations: declarations } }; } function createErrorResult(sourceFile, start, length, message) { return { errors: [ts.createFileDiagnostic(sourceFile, start, length, message)] }; } function checkRootNode(node) { - if (ts.isIdentifier(node)) { + if (ts.isIdentifier(ts.isExpressionStatement(node) ? node.expression : node)) { return [ts.createDiagnosticForNode(node, Messages.InsufficientSelection)]; } return undefined; @@ -89946,7 +90514,7 @@ var ts; PermittedJumps[PermittedJumps["Continue"] = 2] = "Continue"; PermittedJumps[PermittedJumps["Return"] = 4] = "Return"; })(PermittedJumps || (PermittedJumps = {})); - if (!ts.isStatement(nodeToCheck) && !(ts.isExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { + if (!ts.isStatement(nodeToCheck) && !(ts.isPartOfExpression(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)]; } if (ts.isInAmbientContext(nodeToCheck)) { @@ -90010,45 +90578,30 @@ var ts; return false; } var savedPermittedJumps = permittedJumps; - if (node.parent) { - switch (node.parent.kind) { - case 211 /* IfStatement */: - if (node.parent.thenStatement === node || node.parent.elseStatement === node) { - // forbid all jumps inside thenStatement or elseStatement - permittedJumps = 0 /* None */; - } - break; - case 224 /* TryStatement */: - if (node.parent.tryBlock === node) { - // forbid all jumps inside try blocks - permittedJumps = 0 /* None */; - } - else if (node.parent.finallyBlock === node) { - // allow unconditional returns from finally blocks - permittedJumps = 4 /* Return */; - } - break; - case 260 /* CatchClause */: - if (node.parent.block === node) { - // forbid all jumps inside the block of catch clause - permittedJumps = 0 /* None */; - } - break; - case 257 /* CaseClause */: - if (node.expression !== node) { - // allow unlabeled break inside case clauses - permittedJumps |= 1 /* Break */; - } - break; - default: - if (ts.isIterationStatement(node.parent, /*lookInLabeledStatements*/ false)) { - if (node.parent.statement === node) { - // allow unlabeled break/continue inside loops - permittedJumps |= 1 /* Break */ | 2 /* Continue */; - } - } - break; - } + switch (node.kind) { + case 211 /* IfStatement */: + permittedJumps = 0 /* None */; + break; + case 224 /* TryStatement */: + // forbid all jumps inside try blocks + permittedJumps = 0 /* None */; + break; + case 207 /* Block */: + if (node.parent && node.parent.kind === 224 /* TryStatement */ && node.finallyBlock === node) { + // allow unconditional returns from finally blocks + permittedJumps = 4 /* Return */; + } + break; + case 257 /* CaseClause */: + // allow unlabeled break inside case clauses + permittedJumps |= 1 /* Break */; + break; + default: + if (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)) { + // allow unlabeled break/continue inside loops + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; } switch (node.kind) { case 169 /* ThisType */: @@ -90074,7 +90627,7 @@ var ts; } } else { - if (!(permittedJumps & (218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 218 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements)); } @@ -90104,6 +90657,19 @@ var ts; } } extractMethod_1.getRangeToExtract = getRangeToExtract; + function getStatementOrExpressionRange(node) { + if (ts.isStatement(node)) { + return [node]; + } + else if (ts.isPartOfExpression(node)) { + // If our selection is the expression in an ExpressionStatement, expand + // the selection to include the enclosing Statement (this stops us + // from trying to care about the return value of the extracted function + // and eliminates double semicolon insertion in certain scenarios) + return ts.isExpressionStatement(node.parent) ? [node.parent] : node; + } + return undefined; + } function isValidExtractionTarget(node) { // Note that we don't use isFunctionLike because we don't want to put the extracted closure *inside* a method return (node.kind === 228 /* FunctionDeclaration */) || ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isClassLike(node); @@ -90144,14 +90710,29 @@ var ts; } return scopes; } - extractMethod_1.collectEnclosingScopes = collectEnclosingScopes; + // exported only for tests + function getExtractionAtIndex(targetRange, context, requestedChangesIndex) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, errorsPerScope = _b.errorsPerScope; + ts.Debug.assert(!errorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context); + } + extractMethod_1.getExtractionAtIndex = getExtractionAtIndex; /** * Given a piece of text to extract ('targetRange'), computes a list of possible extractions. * Each returned ExtractResultForScope corresponds to a possible target scope and is either a set of changes * or an error explaining why we can't extract into that scope. */ - function getPossibleExtractions(targetRange, context, requestedChangesIndex) { - if (requestedChangesIndex === void 0) { requestedChangesIndex = undefined; } + // exported only for tests + function getPossibleExtractions(targetRange, context) { + var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, errorsPerScope = _a.readsAndWrites.errorsPerScope; + // Need the inner type annotation to avoid https://github.com/Microsoft/TypeScript/issues/7547 + return scopes.map(function (scope, i) { + return ({ scopeDescription: getDescriptionForScope(scope), errors: errorsPerScope[i] }); + }); + } + extractMethod_1.getPossibleExtractions = getPossibleExtractions; + function getPossibleExtractionsWorker(targetRange, context) { var sourceFile = context.file; if (targetRange === undefined) { return undefined; @@ -90161,87 +90742,67 @@ var ts; return undefined; } var enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - var _a = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker()), target = _a.target, usagesPerScope = _a.usagesPerScope, errorsPerScope = _a.errorsPerScope; - context.cancellationToken.throwIfCancellationRequested(); - if (requestedChangesIndex !== undefined) { - if (errorsPerScope[requestedChangesIndex].length) { - return undefined; - } - return [extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange, context)]; - } - else { - return scopes.map(function (scope, i) { - var errors = errorsPerScope[i]; - if (errors.length) { - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - errors: errors - }; - } - return { scope: scope, scopeDescription: getDescriptionForScope(scope) }; - }); - } + var readsAndWrites = collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, context.program.getTypeChecker(), context.cancellationToken); + return { scopes: scopes, readsAndWrites: readsAndWrites }; } - extractMethod_1.getPossibleExtractions = getPossibleExtractions; function getDescriptionForScope(scope) { - if (ts.isFunctionLike(scope)) { - switch (scope.kind) { - case 152 /* Constructor */: - return "constructor"; - case 186 /* FunctionExpression */: - return scope.name - ? "function expression " + scope.name.getText() - : "anonymous function expression"; - case 228 /* FunctionDeclaration */: - return "function " + scope.name.getText(); - case 187 /* ArrowFunction */: - return "arrow function"; - case 151 /* MethodDeclaration */: - return "method " + scope.name.getText(); - case 153 /* GetAccessor */: - return "get " + scope.name.getText(); - case 154 /* SetAccessor */: - return "set " + scope.name.getText(); - } - } - else if (ts.isModuleBlock(scope)) { - return "namespace " + scope.parent.name.getText(); - } - else if (ts.isClassLike(scope)) { - return scope.kind === 229 /* ClassDeclaration */ - ? "class " + scope.name.text - : scope.name.text - ? "class expression " + scope.name.text - : "anonymous class expression"; - } - else if (ts.isSourceFile(scope)) { - return "file '" + scope.fileName + "'"; - } - else { - return "unknown"; + return ts.isFunctionLikeDeclaration(scope) + ? "inner function in " + getDescriptionForFunctionLikeDeclaration(scope) + : ts.isClassLike(scope) + ? "method in " + getDescriptionForClassLikeDeclaration(scope) + : "function in " + getDescriptionForModuleLikeDeclaration(scope); + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 152 /* Constructor */: + return "constructor"; + case 186 /* FunctionExpression */: + return scope.name + ? "function expression '" + scope.name.text + "'" + : "anonymous function expression"; + case 228 /* FunctionDeclaration */: + return "function '" + scope.name.text + "'"; + case 187 /* ArrowFunction */: + return "arrow function"; + case 151 /* MethodDeclaration */: + return "method '" + scope.name.getText(); + case 153 /* GetAccessor */: + return "'get " + scope.name.getText() + "'"; + case 154 /* SetAccessor */: + return "'set " + scope.name.getText() + "'"; + default: + ts.Debug.assertNever(scope); } } - function getUniqueName(isNameOkay) { + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 229 /* ClassDeclaration */ + ? "class '" + scope.name.text + "'" + : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 234 /* ModuleBlock */ + ? "namespace '" + scope.parent.name.getText() + "'" + : scope.externalModuleIndicator ? "module scope" : "global scope"; + } + function getUniqueName(fileText) { var functionNameText = "newFunction"; - if (isNameOkay(functionNameText)) { - return functionNameText; - } - var i = 1; - while (!isNameOkay(functionNameText = "newFunction_" + i)) { - i++; + for (var i = 1; fileText.indexOf(functionNameText) !== -1; i++) { + functionNameText = "newFunction_" + i; } return functionNameText; } + /** + * Result of 'extractRange' operation for a specific scope. + * Stores either a list of changes that should be applied to extract a range or a list of errors + */ function extractFunctionInScope(node, scope, _a, range, context) { - var usagesInScope = _a.usages, substitutions = _a.substitutions; + var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(function (n) { return !file.identifiers.has(n); }); + var functionNameText = getUniqueName(file.text); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); - var functionReference = ts.createIdentifier(functionNameText); var returnType = undefined; var parameters = []; var callArguments = []; @@ -90266,13 +90827,23 @@ var ts; } callArguments.push(ts.createIdentifier(name)); }); - // Provide explicit return types for contexutally-typed functions + var typeParametersAndDeclarations = ts.arrayFrom(typeParameterUsages.values()).map(function (type) { return ({ type: type, declaration: getFirstDeclaration(type) }); }); + var sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + var typeParameters = sortedTypeParametersAndDeclarations.length === 0 + ? undefined + : sortedTypeParametersAndDeclarations.map(function (t) { return t.declaration; }); + // Strictly speaking, we should check whether each name actually binds to the appropriate type + // parameter. In cases of shadowing, they may not. + var callTypeArguments = typeParameters !== undefined + ? typeParameters.map(function (decl) { return ts.createTypeReferenceNode(decl.name, /*typeArguments*/ undefined); }) + : undefined; + // Provide explicit return types for contextually-typed functions // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); returnType = checker.typeToTypeNode(contextualType); } - var _b = transformFunctionBody(node), body = _b.body, returnValueProperty = _b.returnValueProperty; + var _b = transformFunctionBody(node, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; var newFunction; if (ts.isClassLike(scope)) { // always create private method in TypeScript files @@ -90284,22 +90855,27 @@ var ts; modifiers.push(ts.createToken(120 /* AsyncKeyword */)); } newFunction = ts.createMethod( - /*decorators*/ undefined, modifiers, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, - /*questionToken*/ undefined, - /*typeParameters*/ [], parameters, returnType, body); + /*decorators*/ undefined, modifiers.length ? modifiers : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, + /*questionToken*/ undefined, typeParameters, parameters, returnType, body); } else { newFunction = ts.createFunctionDeclaration( - /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, - /*typeParameters*/ [], parameters, returnType, body); + /*decorators*/ undefined, range.facts & RangeFacts.IsAsyncFunction ? [ts.createToken(120 /* AsyncKeyword */)] : undefined, range.facts & RangeFacts.IsGenerator ? ts.createToken(39 /* AsteriskToken */) : undefined, functionName, typeParameters, parameters, returnType, body); + } + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var minInsertionPos = (isReadonlyArray(range.range) ? ts.lastOrUndefined(range.range) : range.range).end; + var nodeToInsertBefore = getNodeToInsertBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newFunction, { suffix: context.newLineCharacter + context.newLineCharacter }); + } + else { + changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); } - var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - // insert function at the end of the scope - changeTracker.insertNodeBefore(context.file, scope.getLastToken(), newFunction, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); var newNodes = []; // replace range with function call - var call = ts.createCall(ts.isClassLike(scope) ? ts.createPropertyAccess(range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.getText()) : ts.createThis(), functionReference) : functionReference, - /*typeArguments*/ undefined, callArguments); + var called = getCalledExpression(scope, range, functionNameText); + var call = ts.createCall(called, callTypeArguments, // Note that no attempt is made to take advantage of type argument inference + callArguments); if (range.facts & RangeFacts.IsGenerator) { call = ts.createYield(ts.createToken(39 /* AsteriskToken */), call); } @@ -90323,6 +90899,9 @@ var ts; } else { newNodes.push(ts.createStatement(ts.createBinary(assignments[0].name, 58 /* EqualsToken */, call))); + if (range.facts & RangeFacts.HasReturn) { + newNodes.push(ts.createReturn()); + } } } else { @@ -90355,67 +90934,164 @@ var ts; else { changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes, { nodeSeparator: context.newLineCharacter }); } - return { - scope: scope, - scopeDescription: getDescriptionForScope(scope), - changes: changeTracker.getChanges() - }; - function getPropertyAssignmentsForWrites(writes) { - return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); - } - function generateReturnValueProperty() { - return "__return"; - } - function transformFunctionBody(body) { - if (ts.isBlock(body) && !writes && substitutions.size === 0) { - // already block, no writes to propagate back, no substitutions - can use node as is - return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; - } - var returnValueProperty; - var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); - // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions - if (writes || substitutions.size) { - var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); - if (writes && !(range.facts & RangeFacts.HasReturn) && ts.isStatement(body)) { - // add return at the end to propagate writes back in case if control flow falls out of the function body - // it is ok to know that range has at least one return since it we only allow unconditional returns - var assignments = getPropertyAssignmentsForWrites(writes); - if (assignments.length === 1) { - rewrittenStatements.push(ts.createReturn(assignments[0].name)); - } - else { - rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); - } + var edits = changeTracker.getChanges(); + var renameRange = isReadonlyArray(range.range) ? range.range[0] : range.range; + var renameFilename = renameRange.getSourceFile().fileName; + var renameLocation = getRenameLocation(edits, renameFilename, functionNameText); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function getRenameLocation(edits, renameFilename, functionNameText) { + var delta = 0; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) { + var change = textChanges_2[_b]; + var span_17 = change.span, newText = change.newText; + // TODO(acasey): We are assuming that the call expression comes before the function declaration, + // because we want the new cursor to be on the call expression, + // which is closer to where the user was before extracting the function. + var index = newText.indexOf(functionNameText); + if (index !== -1) { + return span_17.start + delta + index; + } + delta += newText.length - span_17.length; + } + } + throw new Error(); // Didn't find the text we inserted? + } + function getFirstDeclaration(type) { + var firstDeclaration = undefined; + var symbol = type.symbol; + if (symbol && symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (firstDeclaration === undefined || declaration.pos < firstDeclaration.pos) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder(_a, _b) { + var type1 = _a.type, declaration1 = _a.declaration; + var type2 = _b.type, declaration2 = _b.declaration; + if (declaration1) { + if (declaration2) { + var positionDiff = declaration1.pos - declaration2.pos; + if (positionDiff !== 0) { + return positionDiff; } - return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; } else { - return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; - } - function visitor(node) { - if (node.kind === 219 /* ReturnStatement */ && writes) { - var assignments = getPropertyAssignmentsForWrites(writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = generateReturnValueProperty(); - } - assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); - } - if (assignments.length === 1) { - return ts.createReturn(assignments[0].name); - } - else { - return ts.createReturn(ts.createObjectLiteral(assignments)); + return 1; // Sort undeclared type parameters to the front. + } + } + else if (declaration2) { + return -1; // Sort undeclared type parameters to the front. + } + var name1 = type1.symbol ? type1.symbol.getName() : ""; + var name2 = type2.symbol ? type2.symbol.getName() : ""; + var nameDiff = ts.compareStrings(name1, name2); + if (nameDiff !== 0) { + return nameDiff; + } + // IDs are guaranteed to be unique, so this ensures a total ordering. + return type1.id - type2.id; + } + function getCalledExpression(scope, range, functionNameText) { + var functionReference = ts.createIdentifier(functionNameText); + if (ts.isClassLike(scope)) { + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + return ts.createPropertyAccess(lhs, functionReference); + } + else { + return functionReference; + } + } + function transformFunctionBody(body, writes, substitutions, hasReturn) { + if (ts.isBlock(body) && !writes && substitutions.size === 0) { + // already block, no writes to propagate back, no substitutions - can use node as is + return { body: ts.createBlock(body.statements, /*multLine*/ true), returnValueProperty: undefined }; + } + var returnValueProperty; + var ignoreReturns = false; + var statements = ts.createNodeArray(ts.isBlock(body) ? body.statements.slice(0) : [ts.isStatement(body) ? body : ts.createReturn(body)]); + // rewrite body if either there are writes that should be propagated back via return statements or there are substitutions + if (writes || substitutions.size) { + var rewrittenStatements = ts.visitNodes(statements, visitor).slice(); + if (writes && !hasReturn && ts.isStatement(body)) { + // add return at the end to propagate writes back in case if control flow falls out of the function body + // it is ok to know that range has at least one return since it we only allow unconditional returns + var assignments = getPropertyAssignmentsForWrites(writes); + if (assignments.length === 1) { + rewrittenStatements.push(ts.createReturn(assignments[0].name)); + } + else { + rewrittenStatements.push(ts.createReturn(ts.createObjectLiteral(assignments))); + } + } + return { body: ts.createBlock(rewrittenStatements, /*multiLine*/ true), returnValueProperty: returnValueProperty }; + } + else { + return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; + } + function visitor(node) { + if (!ignoreReturns && node.kind === 219 /* ReturnStatement */ && writes) { + var assignments = getPropertyAssignmentsForWrites(writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; } + assignments.unshift(ts.createPropertyAssignment(returnValueProperty, ts.visitNode(node.expression, visitor))); + } + if (assignments.length === 1) { + return ts.createReturn(assignments[0].name); } else { - var substitution = substitutions.get(ts.getNodeId(node).toString()); - return substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + return ts.createReturn(ts.createObjectLiteral(assignments)); } } + else { + var oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || ts.isFunctionLike(node) || ts.isClassLike(node); + var substitution = substitutions.get(ts.getNodeId(node).toString()); + var result = substitution || ts.visitEachChild(node, visitor, ts.nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function getStatementsOrClassElements(scope) { + if (ts.isFunctionLike(scope)) { + var body = scope.body; + if (ts.isBlock(body)) { + return body.statements; + } + } + else if (ts.isModuleBlock(scope) || ts.isSourceFile(scope)) { + return scope.statements; + } + else if (ts.isClassLike(scope)) { + return scope.members; + } + else { + ts.assertTypeIsNever(scope); } + return ts.emptyArray; + } + /** + * If `scope` contains a function after `minPos`, then return the first such function. + * Otherwise, return `undefined`. + */ + function getNodeToInsertBefore(minPos, scope) { + return ts.find(getStatementsOrClassElements(scope), function (child) { + return child.pos >= minPos && ts.isFunctionLike(child) && !ts.isConstructorDeclaration(child); + }); + } + function getPropertyAssignmentsForWrites(writes) { + return writes.map(function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); } - extractMethod_1.extractFunctionInScope = extractFunctionInScope; function isReadonlyArray(v) { return ts.isArray(v); } @@ -90440,7 +91116,8 @@ var ts; // value should be passed to extracted method and propagated back Usage[Usage["Write"] = 2] = "Write"; })(Usage || (Usage = {})); - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker) { + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + var allTypeParameterUsages = ts.createMap(); // Key is type ID var usagesPerScope = []; var substitutionsPerScope = []; var errorsPerScope = []; @@ -90448,14 +91125,50 @@ var ts; // initialize results for (var _i = 0, scopes_1 = scopes; _i < scopes_1.length; _i++) { var _ = scopes_1[_i]; - usagesPerScope.push({ usages: ts.createMap(), substitutions: ts.createMap() }); + usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); errorsPerScope.push([]); } var seenUsages = ts.createMap(); var target = isReadonlyArray(targetRange.range) ? ts.createBlock(targetRange.range) : targetRange.range; var containingLexicalScopeOfExtraction = ts.isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : ts.getEnclosingBlockScopeContainer(scopes[0]); + var unmodifiedNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + var inGenericContext = isInGenericContext(unmodifiedNode); collectUsages(target); + // Unfortunately, this code takes advantage of the knowledge that the generated method + // will use the contextual type of an expression as the return type of the extracted + // method (and will therefore "use" all the types involved). + if (inGenericContext && !isReadonlyArray(targetRange.range)) { + var contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + var seenTypeParameterUsages = ts.createMap(); // Key is type ID + var i_1 = 0; + for (var curr = unmodifiedNode; curr !== undefined && i_1 < scopes.length; curr = curr.parent) { + if (curr === scopes[i_1]) { + // Copy current contents of seenTypeParameterUsages into scope. + seenTypeParameterUsages.forEach(function (typeParameter, id) { + usagesPerScope[i_1].typeParameterUsages.set(id, typeParameter); + }); + i_1++; + } + // Note that we add the current node's type parameters *after* updating the corresponding scope. + if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { + for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + var typeParameterDecl = _b[_a]; + var typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + // If we didn't get through all the scopes, then there were some that weren't in our + // parent chain (impossible at time of writing). A conservative solution would be to + // copy allTypeParameterUsages into all remaining scopes. + ts.Debug.assert(i_1 === scopes.length); + } var _loop_8 = function (i) { var hasWrite = false; var readonlyClassPropertyWrite = undefined; @@ -90473,7 +91186,7 @@ var ts; errorsPerScope[i].push(ts.createDiagnosticForNode(targetRange.range, Messages.CannotCombineWritesAndReturns)); } else if (readonlyClassPropertyWrite && i > 0) { - errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotCombineWritesAndReturns)); + errorsPerScope[i].push(ts.createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor)); } }; for (var i = 0; i < scopes.length; i++) { @@ -90485,8 +91198,38 @@ var ts; ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } return { target: target, usagesPerScope: usagesPerScope, errorsPerScope: errorsPerScope }; + function hasTypeParameters(node) { + return ts.isDeclarationWithTypeParameters(node) && + node.typeParameters !== undefined && + node.typeParameters.length > 0; + } + function isInGenericContext(node) { + for (; node; node = node.parent) { + if (hasTypeParameters(node)) { + return true; + } + } + return false; + } + function recordTypeParameterUsages(type) { + // PERF: This is potentially very expensive. `type` could be a library type with + // a lot of properties, each of which the walker will visit. Unfortunately, the + // solution isn't as trivial as filtering to user types because of (e.g.) Array. + var symbolWalker = checker.getSymbolWalker(function () { return (cancellationToken.throwIfCancellationRequested(), true); }); + var visitedTypes = symbolWalker.walkType(type).visitedTypes; + for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { + var visitedType = visitedTypes_1[_i]; + if (visitedType.flags & 16384 /* TypeParameter */) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } function collectUsages(node, valueUsage) { if (valueUsage === void 0) { valueUsage = 1 /* Read */; } + if (inGenericContext) { + var type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } if (ts.isDeclaration(node) && node.symbol) { visibleDeclarationsInExtractedRange.push(node.symbol); } @@ -90531,7 +91274,11 @@ var ts; } } function recordUsagebySymbol(identifier, usage, isTypeName) { - var symbol = checker.getSymbolAtLocation(identifier); + // If the identifier is both a property name and its value, we're only interested in its value + // (since the name is a declaration and will be included in the extracted range). + var symbol = identifier.parent && ts.isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier + ? checker.getShorthandAssignmentValueSymbol(identifier.parent) + : checker.getSymbolAtLocation(identifier); if (!symbol) { // cannot find symbol - do nothing return undefined; @@ -90565,7 +91312,7 @@ var ts; if (!declInFile) { return undefined; } - if (ts.rangeContainsRange(enclosingTextRange, declInFile)) { + if (ts.rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { // declaration is located in range to be extracted - do nothing return undefined; } @@ -90589,7 +91336,11 @@ var ts; substitutionsPerScope[i].set(symbolId, substitution); } else if (isTypeName) { - errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + // If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument + // so there's no problem. + if (!(symbol.flags & 262144 /* TypeParameter */)) { + errorsPerScope[i].push(ts.createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope)); + } } else { usagesPerScope[i].usages.set(identifier.text, { usage: usage, symbol: symbol, node: identifier }); @@ -91237,6 +91988,11 @@ var ts; } } break; + case 194 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + addDeclaration(node); + } + // falls through default: ts.forEachChild(node, visit); } @@ -91582,7 +92338,7 @@ var ts; oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || oldSettings.allowJs !== newSettings.allowJs || - oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit || + oldSettings.disableSizeLimit !== newSettings.disableSizeLimit || oldSettings.baseUrl !== newSettings.baseUrl || !ts.equalOwnProperties(oldSettings.paths, newSettings.paths)); // Now create a new compiler @@ -91760,7 +92516,7 @@ var ts; /// Diagnostics function getSyntacticDiagnostics(fileName) { synchronizeHostData(); - return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken).slice(); } /** * getSemanticDiagnostics return array of Diagnostics. If '-d' is not enabled, only report semantic errors @@ -91773,11 +92529,11 @@ var ts; // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); if (!program.getCompilerOptions().declaration) { - return semanticDiagnostics; + return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); - return ts.concatenate(semanticDiagnostics, declarationDiagnostics); + return semanticDiagnostics.concat(declarationDiagnostics); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); @@ -91806,7 +92562,7 @@ var ts; return undefined; } var typeChecker = program.getTypeChecker(); - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { @@ -91841,6 +92597,20 @@ var ts; tags: displayPartsDocumentationsAndKind.tags }; } + function getSymbolAtLocationForQuickInfo(node, checker) { + if ((ts.isIdentifier(node) || ts.isStringLiteral(node)) + && ts.isPropertyAssignment(node.parent) + && node.parent.name === node) { + var type = checker.getContextualType(node.parent.parent); + if (type) { + var property = checker.getPropertyOfType(type, ts.getTextOfIdentifierOrLiteral(node)); + if (property) { + return property; + } + } + } + return checker.getSymbolAtLocation(node); + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); @@ -91903,7 +92673,20 @@ var ts; } function getReferences(fileName, position, options) { synchronizeHostData(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = []; + if (options && options.isForRename) { + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (!program.isSourceFileDefaultLibrary(sourceFile)) { + sourceFiles.push(sourceFile); + } + } + } + else { + sourceFiles = program.getSourceFiles().slice(); + } + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); } function findReferences(fileName, position) { synchronizeHostData(); @@ -92304,7 +93087,7 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: host.getNewLine(), + newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), rulesProvider: getRuleProvider(formatOptions), cancellationToken: cancellationToken }; @@ -92385,7 +93168,7 @@ var ts; nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } ts.forEachChild(node, walk); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; ts.forEachChild(jsDoc, walk); diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 5f69ba3ddcddf..af4a4c801b263 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -705,6 +705,7 @@ var ts; TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes"; TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 6368] = "Unit"; TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy"; TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy"; @@ -1065,6 +1066,7 @@ var ts; EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; + EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1097,7 +1099,8 @@ var ts; EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile"; EmitHint[EmitHint["Expression"] = 1] = "Expression"; EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName"; - EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified"; + EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; + EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); })(ts || (ts = {})); var ts; @@ -1164,6 +1167,12 @@ var ts; ts.versionMajorMinor = "2.6"; ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); +(function (ts) { + function isExternalModuleNameRelative(moduleName) { + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; +})(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; @@ -1795,6 +1804,26 @@ var ts; return to; } ts.addRange = addRange; + function pushIfUnique(array, toAdd) { + if (contains(array, toAdd)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + function appendIfUnique(array, toAdd) { + if (array) { + pushIfUnique(array, toAdd); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; function stableSort(array, comparer) { if (comparer === void 0) { comparer = compareValues; } return array @@ -1941,6 +1970,16 @@ var ts; return keys; } ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; function arrayFrom(iterator, map) { var result = []; for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { @@ -2105,6 +2144,8 @@ var ts; ts.cast = cast; function noop() { } ts.noop = noop; + function identity(x) { return x; } + ts.identity = identity; function notImplemented() { throw new Error("Not implemented"); } @@ -2181,12 +2222,11 @@ var ts; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { - var end = start + length; Debug.assertGreaterThanOrEqual(start, 0); Debug.assertGreaterThanOrEqual(length, 0); if (file) { Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(end, file.text.length); + Debug.assertLessThanOrEqual(start + length, file.text.length); } var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { @@ -2428,12 +2468,8 @@ var ts; return /^\.\.?($|[\\/])/.test(path); } ts.pathIsRelative = pathIsRelative; - function isExternalModuleNameRelative(moduleName) { - return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function moduleHasNonRelativeName(moduleName) { - return !isExternalModuleNameRelative(moduleName); + return !ts.isExternalModuleNameRelative(moduleName); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { @@ -2470,7 +2506,7 @@ var ts; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { - return getRootLength(path) !== 0; + return path && getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { @@ -3096,6 +3132,10 @@ var ts; throw e; } Debug.fail = fail; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -3233,6 +3273,12 @@ var ts; return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function assertTypeIsNever(_) { } + ts.assertTypeIsNever = assertTypeIsNever; })(ts || (ts = {})); var ts; (function (ts) { @@ -3797,8 +3843,8 @@ var ts; An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."), - Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), - Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead."), + Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202", "Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."), + Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203", "Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."), Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), @@ -4118,7 +4164,9 @@ var ts; Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it: diag(2560, ts.DiagnosticCategory.Error, "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560", "Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"), - Base_class_expressions_cannot_reference_class_type_parameters: diag(2561, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2561", "Base class expressions cannot reference class type parameters."), + Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2: diag(2561, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561", "Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"), + Base_class_expressions_cannot_reference_class_type_parameters: diag(2562, ts.DiagnosticCategory.Error, "Base_class_expressions_cannot_reference_class_type_parameters_2562", "Base class expressions cannot reference class type parameters."), + The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4191,6 +4239,7 @@ var ts; A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context: diag(2714, ts.DiagnosticCategory.Error, "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714", "The expression of an export assignment must be an identifier or qualified name in an ambient context."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4308,7 +4357,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), - Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), @@ -4413,17 +4462,16 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), - Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), @@ -4514,6 +4562,7 @@ var ts; Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags: diag(8021, ts.DiagnosticCategory.Error, "JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021", "JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4561,7 +4610,7 @@ var ts; Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), Extract_function: diag(95003, ts.DiagnosticCategory.Message, "Extract_function_95003", "Extract function"), - Extract_function_into_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_function_into_0_95004", "Extract function into '{0}'"), + Extract_to_0: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_95004", "Extract to {0}"), }; })(ts || (ts = {})); var ts; @@ -4583,7 +4632,6 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; var stringWriter = createSingleLineStringWriter(); - var stringWriterAcquired = false; function createSingleLineStringWriter() { var str = ""; var writeText = function (text) { return str += text; }; @@ -4607,15 +4655,14 @@ var ts; }; } function usingSingleLineStringWriter(action) { + var oldString = stringWriter.string(); try { - ts.Debug.assert(!stringWriterAcquired); - stringWriterAcquired = true; action(stringWriter); return stringWriter.string(); } finally { stringWriter.clear(); - stringWriterAcquired = false; + stringWriter.writeKeyword(oldString); } } ts.usingSingleLineStringWriter = usingSingleLineStringWriter; @@ -4649,7 +4696,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.version === b.version; + return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; @@ -4771,7 +4818,7 @@ var ts; if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + if (includeJsDoc && ts.hasJSDocNodes(node)) { return getTokenPosOfNode(node.jsDoc[0]); } if (node.kind === 286 && node._children.length > 0) { @@ -4808,6 +4855,15 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function indexOfNode(nodeArray, node) { + return ts.binarySearch(nodeArray, node, compareNodePos); + } + ts.indexOfNode = indexOfNode; + function compareNodePos(_a, _b) { + var aPos = _a.pos; + var bPos = _b.pos; + return aPos < bPos ? -1 : bPos < aPos ? 1 : 0; + } function getEmitFlags(node) { var emitNode = node.emitNode; return emitNode && emitNode.flags; @@ -4835,6 +4891,7 @@ var ts; case 16: return "}" + escapeText(node.text, 96) + "`"; case 8: + case 12: return node.text; } ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); @@ -4932,6 +4989,34 @@ var ts; return false; } ts.isBlockScope = isBlockScope; + function isDeclarationWithTypeParameters(node) { + switch (node.kind) { + case 155: + case 156: + case 150: + case 157: + case 160: + case 161: + case 273: + case 229: + case 199: + case 230: + case 231: + case 282: + case 228: + case 151: + case 152: + case 153: + case 154: + case 186: + case 187: + return true; + default: + ts.assertTypeIsNever(node); + return false; + } + } + ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function getEnclosingBlockScopeContainer(node) { var current = node.parent; while (current) { @@ -5579,59 +5664,62 @@ var ts; case 8: case 9: case 99: - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: - return parent.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: - return parent.expression === node; - case 214: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215: - case 216: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || - forInStatement.expression === node; - case 184: - case 202: - return node === parent.expression; - case 205: - return node === parent.expression; - case 144: - return node === parent.expression; - case 147: - case 256: - case 255: - case 263: - return true; - case 201: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + return isInExpressionContext(node); + default: + return false; } - return false; } ts.isPartOfExpression = isPartOfExpression; + function isInExpressionContext(node) { + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + return isPartOfExpression(parent); + } + } + ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -5795,14 +5883,6 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 279); - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); - } function getAllJSDocs(node) { if (ts.isJSDocTypedefTag(node)) { return [node.parent]; @@ -5810,14 +5890,6 @@ var ts; return getJSDocCommentsAndTags(node); } ts.getAllJSDocs = getAllJSDocs; - function getJSDocTags(node) { - var tags = node.jsDocCache; - if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); - } - return tags; - } - ts.getJSDocTags = getJSDocTags; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -5849,22 +5921,17 @@ var ts; getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - result = ts.addRange(result, getJSDocParameterTags(node)); + result = ts.addRange(result, ts.getJSDocParameterTags(node)); } - if (isVariableLike(node) && node.initializer) { + if (isVariableLike(node) && node.initializer && ts.hasJSDocNodes(node.initializer)) { result = ts.addRange(result, node.initializer.jsDoc); } - result = ts.addRange(result, node.jsDoc); - } - } - function getJSDocParameterTags(param) { - if (param.name && ts.isIdentifier(param.name)) { - var name_1 = param.name.escapedText; - return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + if (ts.hasJSDocNodes(node)) { + result = ts.addRange(result, node.jsDoc); + } } - return undefined; } - ts.getJSDocParameterTags = getJSDocParameterTags; + ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; function getParameterSymbolFromJSDoc(node) { if (node.symbol) { return node.symbol; @@ -5890,38 +5957,6 @@ var ts; return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); } ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 281); - if (!tag && node.kind === 146) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 277); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 278); - } - ts.getJSDocClassTag = getJSDocClassTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 280); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocReturnType(node) { - var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; - } - ts.getJSDocReturnType = getJSDocReturnType; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 282); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { return isRestParameter(ts.lastOrUndefined(s.parameters)); } @@ -5933,7 +5968,7 @@ var ts; function isRestParameter(node) { if (isInJavaScriptFile(node)) { if (node.type && node.type.kind === 274 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + ts.forEach(ts.getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -6334,9 +6369,9 @@ var ts; || kind === 265; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); + function nodeIsSynthesized(range) { + return ts.positionIsSynthesized(range.pos) + || ts.positionIsSynthesized(range.end); } ts.nodeIsSynthesized = nodeIsSynthesized; function getOriginalSourceFile(sourceFile) { @@ -6600,13 +6635,17 @@ var ts; "\u2029": "\\u2029", "\u0085": "\\u0085" }); + var escapedNullRegExp = /\\0[0-9]/g; function escapeString(s, quoteChar) { var escapedCharsRegExp = quoteChar === 96 ? backtickQuoteEscapedCharsRegExp : quoteChar === 39 ? singleQuoteEscapedCharsRegExp : doubleQuoteEscapedCharsRegExp; - return s.replace(escapedCharsRegExp, getReplacement); + return s.replace(escapedCharsRegExp, getReplacement).replace(escapedNullRegExp, nullReplacement); } ts.escapeString = escapeString; + function nullReplacement(c) { + return "\\x00" + c.charAt(c.length - 1); + } function getReplacement(c) { return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } @@ -6886,7 +6925,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocType(node); + return ts.getJSDocType(node); } } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; @@ -6895,7 +6934,7 @@ var ts; return node.type; } if (isInJavaScriptFile(node)) { - return getJSDocReturnType(node); + return ts.getJSDocReturnType(node); } } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; @@ -6904,7 +6943,7 @@ var ts; return node.typeParameters; } if (isInJavaScriptFile(node)) { - var templateTag = getJSDocTemplateTag(node); + var templateTag = ts.getJSDocTemplateTag(node); return templateTag && templateTag.typeParameters; } } @@ -7463,6 +7502,41 @@ var ts; return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; + function isWriteOnlyAccess(node) { + return accessKind(node) === 1; + } + ts.isWriteOnlyAccess = isWriteOnlyAccess; + function isWriteAccess(node) { + return accessKind(node) !== 0; + } + ts.isWriteAccess = isWriteAccess; + var AccessKind; + (function (AccessKind) { + AccessKind[AccessKind["Read"] = 0] = "Read"; + AccessKind[AccessKind["Write"] = 1] = "Write"; + AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite"; + })(AccessKind || (AccessKind = {})); + function accessKind(node) { + var parent = node.parent; + if (!parent) + return 0; + switch (parent.kind) { + case 193: + case 192: + var operator = parent.operator; + return operator === 43 || operator === 44 ? writeOrReadWrite() : 0; + case 194: + var _a = parent, left = _a.left, operatorToken = _a.operatorToken; + return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0; + case 179: + return parent.name !== node ? 0 : accessKind(parent); + default: + return 0; + } + function writeOrReadWrite() { + return parent.parent && parent.parent.kind === 210 ? 1 : 2; + } + } })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -7741,6 +7815,56 @@ var ts; return id; } ts.unescapeIdentifier = unescapeIdentifier; + function nameForNamelessJSDocTypedef(declaration) { + var hostNode = declaration.parent.parent; + if (!hostNode) { + return undefined; + } + if (ts.isDeclaration(hostNode)) { + return getDeclarationIdentifier(hostNode); + } + switch (hostNode.kind) { + case 208: + if (hostNode.declarationList && + hostNode.declarationList.declarations[0]) { + return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + } + return undefined; + case 210: + var expr = hostNode.expression; + switch (expr.kind) { + case 179: + return expr.name; + case 180: + var arg = expr.argumentExpression; + if (ts.isIdentifier(arg)) { + return arg; + } + } + return undefined; + case 1: + return undefined; + case 185: { + return getDeclarationIdentifier(hostNode.expression); + } + case 222: { + if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { + return getDeclarationIdentifier(hostNode.statement); + } + return undefined; + } + default: + ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); + } + } + function getDeclarationIdentifier(node) { + var name = getNameOfDeclaration(node); + return ts.isIdentifier(name) ? name : undefined; + } + function getNameOfJSDocTypedef(declaration) { + return declaration.name || nameForNamelessJSDocTypedef(declaration); + } + ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef; function getNameOfDeclaration(declaration) { if (!declaration) { return undefined; @@ -7760,11 +7884,78 @@ var ts; return undefined; } } + else if (declaration.kind === 283) { + return getNameOfJSDocTypedef(declaration); + } else { return declaration.name; } } ts.getNameOfDeclaration = getNameOfDeclaration; + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getJSDocTypeTag(node) { + var tag = getFirstJSDocTag(node, 281); + if (tag && tag.typeExpression && tag.typeExpression.type) { + return tag; + } + return undefined; + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } })(ts || (ts = {})); (function (ts) { function isNumericLiteral(node) { @@ -8397,8 +8588,7 @@ var ts; } ts.isToken = isToken; function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); + return array.hasOwnProperty("pos") && array.hasOwnProperty("end"); } ts.isNodeArray = isNodeArray; function isLiteralKind(kind) { @@ -8483,16 +8673,27 @@ var ts; return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { + function isFunctionLikeDeclaration(node) { + return node && isFunctionLikeDeclarationKind(node.kind); + } + ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; + function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 152: - case 186: case 228: - case 187: case 151: - case 150: + case 152: case 153: case 154: + case 186: + case 187: + return true; + default: + return false; + } + } + function isFunctionLikeKind(kind) { + switch (kind) { + case 150: case 155: case 156: case 157: @@ -8500,10 +8701,15 @@ var ts; case 273: case 161: return true; + default: + return isFunctionLikeDeclarationKind(kind); } - return false; } ts.isFunctionLikeKind = isFunctionLikeKind; + function isFunctionOrModuleBlock(node) { + return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent); + } + ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock; function isClassElement(node) { var kind = node.kind; return kind === 152 @@ -8657,52 +8863,61 @@ var ts; || kind === 13; } ts.isTemplateLiteral = isTemplateLiteral; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 91 - || kind === 203 - || kind === 204; - } function isLeftHandSideExpression(node) { return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); + function isLeftHandSideExpressionKind(kind) { + switch (kind) { + case 179: + case 180: + case 182: + case 181: + case 249: + case 250: + case 183: + case 177: + case 185: + case 178: + case 199: + case 186: + case 71: + case 12: + case 8: + case 9: + case 13: + case 196: + case 86: + case 95: + case 99: + case 101: + case 97: + case 203: + case 204: + case 91: + return true; + default: + return false; + } } function isUnaryExpression(node) { return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isUnaryExpression = isUnaryExpression; + function isUnaryExpressionKind(kind) { + switch (kind) { + case 192: + case 193: + case 188: + case 189: + case 190: + case 191: + case 184: + return true; + default: + return isLeftHandSideExpressionKind(kind); + } + } function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { case 193: @@ -8715,21 +8930,26 @@ var ts; } } ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 289 - || isUnaryExpressionKind(kind); - } function isExpression(node) { return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); } ts.isExpression = isExpression; + function isExpressionKind(kind) { + switch (kind) { + case 195: + case 197: + case 187: + case 194: + case 198: + case 202: + case 200: + case 289: + case 288: + return true; + default: + return isUnaryExpressionKind(kind); + } + } function isAssertionExpression(node) { var kind = node.kind; return kind === 184 @@ -8970,6 +9190,10 @@ var ts; return node.kind >= 276 && node.kind <= 285; } ts.isJSDocTag = isJSDocTag; + function hasJSDocNodes(node) { + return !!node.jsDoc && node.jsDoc.length > 0; + } + ts.hasJSDocNodes = hasJSDocNodes; })(ts || (ts = {})); var ts; (function (ts) { @@ -9196,7 +9420,7 @@ var ts; ts.Debug.assert(res < lineStarts[line + 1]); } else if (debugText !== undefined) { - ts.Debug.assert(res < debugText.length); + ts.Debug.assert(res <= debugText.length); } return res; } @@ -10987,9 +11211,11 @@ var ts; visitNode(cbNode, node.typeExpression); } case 285: - for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { - var tag = _a[_i]; - visitNode(cbNode, tag); + if (node.jsDocPropertyTags) { + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } } return; case 288: @@ -11169,7 +11395,7 @@ var ts; var saveParent = parent; parent = n; forEachChild(n, visitNode); - if (n.jsDoc) { + if (ts.hasJSDocNodes(n)) { for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { var jsDoc = _a[_i]; jsDoc.parent = n; @@ -11289,9 +11515,6 @@ var ts; function getNodePos() { return scanner.getStartPos(); } - function getNodeEnd() { - return scanner.getStartPos(); - } function token() { return currentToken; } @@ -11414,13 +11637,11 @@ var ts; kind === 71 ? new IdentifierConstructor(kind, pos, pos) : new TokenConstructor(kind, pos, pos); } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } + function createNodeArray(elements, pos, end) { + var length = elements.length; + var array = (length >= 1 && length <= 4 ? elements.slice() : elements); array.pos = pos; - array.end = pos; + array.end = end === undefined ? scanner.getStartPos() : end; return array; } function finishNode(node, end) { @@ -11468,7 +11689,8 @@ var ts; nextToken(); return finishNode(node); } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var reportAtCurrentPosition = token() === 1; + return createMissingNode(71, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -11701,20 +11923,20 @@ var ts; function parseList(kind, parseElement) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { var element = parseListElement(kind, parseElement); - result.push(element); + list.push(element); continue; } if (abortParsingListOrMoveToNextToken(kind)) { break; } } - result.end = getNodeEnd(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseListElement(parsingContext, parseElement) { var node = currentNode(parsingContext); @@ -11920,12 +12142,13 @@ var ts; function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { var saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var commaStart = -1; while (true) { if (isListElement(kind, false)) { var startPos = scanner.getStartPos(); - result.push(parseListElement(kind, parseElement)); + list.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(26)) { continue; @@ -11950,15 +12173,15 @@ var ts; break; } } + parsingContext = saveParsingContext; + var result = createNodeArray(list, listPos); if (commaStart >= 0) { result.hasTrailingComma = true; } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; return result; } function createMissingList() { - return createNodeArray(); + return createNodeArray([], getNodePos()); } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -12000,12 +12223,12 @@ var ts; var template = createNode(196); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); + var list = []; + var listPos = getNodePos(); do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; + list.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(list).literal.kind === 15); + template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { @@ -12100,7 +12323,7 @@ var ts; var result = createNode(273); nextToken(); fillSignature(56, 4 | 32, result); - return finishNode(result); + return addJSDocComment(finishNode(result)); } var node = createNode(159); node.typeName = parseIdentifierName(); @@ -12158,9 +12381,10 @@ var ts; return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || - token() === 57 || isStartOfType(); + token() === 57 || + isStartOfType(true); } - function parseParameter() { + function parseParameter(requireEqualsToken) { var node = createNode(146); if (token() === 99) { node.name = createIdentifier(true); @@ -12176,37 +12400,33 @@ var ts; } node.questionToken = parseOptionalToken(55); node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); + node.initializer = parseInitializer(true, requireEqualsToken); return addJSDocComment(finishNode(node)); } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } function fillSignature(returnToken, flags, signature) { if (!(flags & 32)) { signature.typeParameters = parseTypeParameters(); } signature.parameters = parseParameterList(flags); - var returnTokenRequired = returnToken === 36; - if (returnTokenRequired) { + signature.type = parseReturnType(returnToken, !!(flags & 4)); + } + function parseReturnType(returnToken, isType) { + return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + } + function shouldParseReturnType(returnToken, isType) { + if (returnToken === 36) { parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); + return true; } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); + else if (parseOptional(56)) { + return true; } - else if (flags & 4) { - var start = scanner.getTokenPos(); - var length_1 = scanner.getTextPos() - start; - var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); - if (backwardToken) { - signature.type = parseTypeOrTypePredicate(); - parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); - } + else if (isType && token() === 36) { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(56)); + nextToken(); + return true; } + return false; } function parseParameterList(flags) { if (parseExpected(19)) { @@ -12214,7 +12434,7 @@ var ts; var savedAwaitContext = inAwaitContext(); setYieldContext(!!(flags & 1)); setAwaitContext(!!(flags & 2)); - var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : function () { return parseParameter(!!(flags & 8)); }); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); if (!parseExpected(20) && (flags & 8)) { @@ -12278,7 +12498,7 @@ var ts; node.parameters = parseBracketedList(16, parseParameter, 21, 22); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parsePropertyOrMethodSignature(fullStart, modifiers) { var name = parsePropertyName(); @@ -12410,7 +12630,7 @@ var ts; parseExpected(94); } fillSignature(36, 4, node); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseKeywordAndNoDot() { var node = parseTokenNode(); @@ -12424,16 +12644,9 @@ var ts; unaryMinusExpression.operator = 38; nextToken(); } - var expression; - switch (token()) { - case 9: - case 8: - expression = parseLiteralLikeNode(token()); - break; - case 101: - case 86: - expression = parseTokenNode(); - } + var expression = token() === 101 || token() === 86 + ? parseTokenNode() + : parseLiteralLikeNode(token()); if (negative) { unaryMinusExpression.operand = expression; finishNode(unaryMinusExpression); @@ -12466,6 +12679,7 @@ var ts; return parseJSDocNodeWithType(274); case 51: return parseJSDocNodeWithType(271); + case 13: case 9: case 8: case 101: @@ -12497,7 +12711,7 @@ var ts; return parseTypeReference(); } } - function isStartOfType() { + function isStartOfType(inStartOfParameter) { switch (token()) { case 119: case 136: @@ -12522,11 +12736,14 @@ var ts; case 86: case 134: case 39: + case 55: + case 51: + case 24: return true; case 38: - return lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); + return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); default: return isIdentifier(); } @@ -12592,13 +12809,12 @@ var ts; parseOptional(operator); var type = parseConstituentType(); if (token() === operator) { - var types = createNodeArray([type], type.pos); + var types = [type]; while (parseOptional(operator)) { types.push(parseConstituentType()); } - types.end = getNodeEnd(); var node = createNode(kind, type.pos); - node.types = types; + node.types = createNodeArray(types, type.pos); type = finishNode(node); } return type; @@ -12758,11 +12974,16 @@ var ts; } return expr; } - function parseInitializer(inParameter) { + function parseInitializer(inParameter, requireEqualsToken) { if (token() !== 58) { if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { return undefined; } + if (inParameter && requireEqualsToken) { + var result = createMissingNode(71, true, ts.Diagnostics._0_expected, "="); + result.escapedText = "= not found"; + return result; + } } parseExpected(58); return parseAssignmentExpressionOrHigher(); @@ -12823,8 +13044,7 @@ var ts; var parameter = createNode(146, identifier.pos); parameter.name = identifier; finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; + node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(!!asyncModifier); return addJSDocComment(finishNode(node)); @@ -12931,8 +13151,7 @@ var ts; } function tryParseAsyncSimpleArrowFunctionExpression() { if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { + if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1) { var asyncModifier = parseModifiersForArrowFunction(); var expr = parseBinaryExpressionOrHigher(0); return parseSimpleArrowFunctionExpression(expr, asyncModifier); @@ -12961,7 +13180,8 @@ var ts; if (!node.parameters) { return undefined; } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { + if (!allowAmbiguity && ((token() !== 36 && token() !== 17) || + ts.find(node.parameters, function (p) { return p.initializer && ts.isIdentifier(p.initializer) && p.initializer.escapedText === "= not found"; }))) { return undefined; } return node; @@ -13303,7 +13523,8 @@ var ts; ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTagName) { - var result = createNodeArray(); + var list = []; + var listPos = getNodePos(); var saveParsingContext = parsingContext; parsingContext |= 1 << 14; while (true) { @@ -13320,12 +13541,11 @@ var ts; } var child = parseJsxChild(); if (child) { - result.push(child); + list.push(child); } } - result.end = scanner.getTokenPos(); parsingContext = saveParsingContext; - return result; + return createNodeArray(list, listPos); } function parseJsxAttributes() { var jsxAttributes = createNode(254); @@ -14204,7 +14424,7 @@ var ts; var node = createNode(176); node.dotDotDotToken = parseOptionalToken(24); node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingElement() { @@ -14220,7 +14440,7 @@ var ts; node.propertyName = propertyName; node.name = parseIdentifierOrPattern(); } - node.initializer = parseBindingElementInitializer(false); + node.initializer = parseInitializer(false); return finishNode(node); } function parseObjectBindingPattern() { @@ -14254,7 +14474,7 @@ var ts; node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); + node.initializer = parseNonParameterInitializer(); } return finishNode(node); } @@ -14418,7 +14638,8 @@ var ts; return false; } function parseDecorators() { - var decorators; + var list; + var listPos = getNodePos(); while (true) { var decoratorStart = getNodePos(); if (!parseOptional(57)) { @@ -14427,20 +14648,13 @@ var ts; var decorator = createNode(147, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } + (list || (list = [])).push(decorator); } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; + return list && createNodeArray(list, listPos); } function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; + var list; + var listPos = getNodePos(); while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); @@ -14455,17 +14669,9 @@ var ts; } } var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } + (list || (list = [])).push(modifier); } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; + return list && createNodeArray(list, listPos); } function parseModifiersForArrowFunction() { var modifiers; @@ -14475,7 +14681,6 @@ var ts; nextToken(); var modifier = finishNode(createNode(modifierKind, modifierStart)); modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); } return modifiers; } @@ -14970,9 +15175,11 @@ var ts; return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - function parseJSDocTypeExpression() { + function parseJSDocTypeExpression(requireBraces) { var result = createNode(267, scanner.getTokenPos()); - parseExpected(17); + if (!parseExpected(17) && requireBraces) { + return undefined; + } result.type = doInsideOfContext(1048576, parseType); parseExpected(18); fixupParentReferences(result); @@ -15029,6 +15236,8 @@ var ts; ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); var tags; + var tagsPos; + var tagsEnd; var comments = []; var result; if (!isJsDocStart(content, start)) { @@ -15137,7 +15346,7 @@ var ts; } function createJSDocComment() { var result = createNode(275, start); - result.tags = tags; + result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } @@ -15260,21 +15469,17 @@ var ts; function addTag(tag, comments) { tag.comment = comments.join(""); if (!tags) { - tags = createNodeArray([tag], tag.pos); + tags = [tag]; + tagsPos = tag.pos; } else { tags.push(tag); } - tags.end = tag.end; + tagsEnd = tag.end; } function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); + skipWhitespace(); + return token() === 17 ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { var isBracketed = parseOptional(21); @@ -15364,11 +15569,11 @@ var ts; var result = createNode(281, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); + result.typeExpression = parseJSDocTypeExpression(true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); + var typeExpression = parseJSDocTypeExpression(true); var result = createNode(277, atToken.pos); result.atToken = atToken; result.tagName = tagName; @@ -15403,19 +15608,18 @@ var ts; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; - var alreadyHasTypeTag = false; + var childTypeTag = void 0; var start_3 = scanner.getStartPos(); while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(285, start_3); } if (child.kind === 281) { - if (alreadyHasTypeTag) { + if (childTypeTag) { break; } else { - jsdocTypeLiteral.jsDocTypeTag = child; - alreadyHasTypeTag = true; + childTypeTag = child; } } else { @@ -15429,7 +15633,9 @@ var ts; if (typeExpression && typeExpression.type.kind === 164) { jsdocTypeLiteral.isArrayType = true; } - typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + typedefTag.typeExpression = childTypeTag && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? + childTypeTag.typeExpression : + finishNode(jsdocTypeLiteral); } } return finishNode(typedefTag); @@ -15523,7 +15729,8 @@ var ts; if (ts.forEach(tags, function (t) { return t.kind === 282; })) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var typeParameters = createNodeArray(); + var typeParameters = []; + var typeParametersPos = getNodePos(); while (true) { var name = parseJSDocIdentifierName(); skipWhitespace(); @@ -15546,9 +15753,8 @@ var ts; var result = createNode(282, atToken.pos); result.atToken = atToken; result.tagName = tagName; - result.typeParameters = typeParameters; + result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); - typeParameters.end = result.end; return result; } function nextJSDocToken() { @@ -15640,7 +15846,7 @@ var ts; ts.Debug.assert(text === newText.substring(node.pos, node.end)); } forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { + if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; forEachChild(jsDocComment, visitNode, visitArray); @@ -16814,7 +17020,7 @@ var ts; errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); } var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined" && typeof value !== "undefined") { + if (typeof keyText !== "undefined") { result[keyText] = value; if (jsonConversionNotifier && (parentOption || knownOptions === knownRootOptions)) { @@ -16849,7 +17055,7 @@ var ts; reportInvalidOptionValue(option && option.type !== "boolean"); return false; case 95: - reportInvalidOptionValue(!!option); + reportInvalidOptionValue(option && option.name === "extends"); return null; case 9: if (!isDoubleQuotedString(valueExpression)) { @@ -16905,6 +17111,8 @@ var ts; } function isCompilerOptionsValue(option, value) { if (option) { + if (isNullOrUndefined(value)) + return true; if (option.type === "list") { return ts.isArray(value); } @@ -17057,6 +17265,12 @@ var ts; } } ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + return ts.getDirectoryPath(ts.toPath(fileName, basePath, ts.identity)); + } function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } @@ -17080,7 +17294,7 @@ var ts; }; function getFileNames() { var fileNames; - if (ts.hasProperty(raw, "files")) { + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw["files"])) { if (ts.isArray(raw["files"])) { fileNames = raw["files"]; if (fileNames.length === 0) { @@ -17092,7 +17306,7 @@ var ts; } } var includeSpecs; - if (ts.hasProperty(raw, "include")) { + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw["include"])) { if (ts.isArray(raw["include"])) { includeSpecs = raw["include"]; } @@ -17101,7 +17315,7 @@ var ts; } } var excludeSpecs; - if (ts.hasProperty(raw, "exclude")) { + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw["exclude"])) { if (ts.isArray(raw["exclude"])) { excludeSpecs = raw["exclude"]; } @@ -17118,7 +17332,7 @@ var ts; if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } @@ -17180,7 +17394,8 @@ var ts; errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); } else { - extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; @@ -17202,7 +17417,8 @@ var ts; onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { switch (key) { case "extends": - extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, getCanonicalFileName, errors, function (message, arg0) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; @@ -17356,6 +17572,8 @@ var ts; } } function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; if (option.type === "list") { var listOption_1 = option; if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { @@ -17378,6 +17596,8 @@ var ts; return value; } function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; var key = value.toLowerCase(); var val = opt.type.get(key); if (val !== undefined) { @@ -17414,7 +17634,7 @@ var ts; if (fileNames) { for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var fileName = fileNames_1[_i]; - var file = ts.combinePaths(basePath, fileName); + var file = ts.getNormalizedAbsolutePath(fileName, basePath); literalFileMap.set(keyMapper(file), file); } } @@ -17806,7 +18026,7 @@ var ts; return undefined; } ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; + return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { return { @@ -17909,12 +18129,12 @@ var ts; var resolvedTypeReferenceDirective; if (resolved) { if (!options.preserveSymlinks) { - resolved = realPath(resolved, host, traceEnabled); + resolved = __assign({}, resolved, { fileName: realPath(resolved.fileName, host, traceEnabled) }); } if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; } return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; function primaryLookup() { @@ -18211,7 +18431,7 @@ var ts; if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); if (path_1 !== undefined) { - return { path: path_1, extension: extension, packageId: undefined }; + return noPackageId({ path: path_1, ext: extension }); } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); @@ -18373,31 +18593,40 @@ var ts; } function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } + var _a = considerPackageJson + ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) + : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + } + function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { + var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - var packageId; - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var jsonContent = readJson(packageJsonPath, state.host); - if (typeof jsonContent.name === "string" && typeof jsonContent.version === "string") { - packageId = { name: jsonContent.name, version: jsonContent.version }; - } - var fromPackageJson = loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return withPackageId(packageId, fromPackageJson); - } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, _a) { + var host = _a.host, traceEnabled = _a.traceEnabled; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); + var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + if (directoryExists && host.fileExists(packageJsonPath)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); + var packageJsonContent = readJson(packageJsonPath, host); + var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" + ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } + : undefined; + return { packageJsonContent: packageJsonContent, packageId: packageId }; + } + else { + if (directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); + return { packageJsonContent: undefined, packageId: undefined }; } - return withPackageId(packageId, loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state)); } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); @@ -18440,9 +18669,20 @@ var ts; return ts.combinePaths(directory, "package.json"); } function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); + var _b = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state), packageJsonContent = _b.packageJsonContent, packageId = _b.packageId; var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); + return withPackageId(packageId, pathAndExtension); + } + function getPackageName(moduleName) { + var idx = moduleName.indexOf(ts.directorySeparator); + if (moduleName[0] === "@") { + idx = moduleName.indexOf(ts.directorySeparator, idx + 1); + } + return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache);